All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.guppy4j.exceptions.TryCatchConvertThrow Maven / Gradle / Ivy

There is a newer version: 0.0.7
Show newest version
package org.guppy4j.exceptions;

import java.util.function.Function;

/**
 * Attempts to execute functions or actions that can throw a certain checked exception type E,
 * handles those exceptions and converts them to an unchecked exception
 */
public final class TryCatchConvertThrow implements ExceptionHandler {

    private final Class exType;
    private final Function exConverter;

    public TryCatchConvertThrow(Class exType, Function exConverter) {
        if (RuntimeException.class.isAssignableFrom(exType)) {
            throw new IllegalArgumentException(exType + " must be a checked exception type");
        }
        this.exType = exType;
        this.exConverter = exConverter;
    }

    /**
     * Executes the action, catches any checked exception of type E,
     * converts (usually wraps) it to an RE and throws that.
     * Any other
     *
     * @param action The action to execute that might throw an E
     */
    @Override
    public void tryUnchecked(ActionToTry action) {
        tryUnchecked(noParam -> {
            action.execute();
            return null;
        }, null);
    }

    @Override
    public  R tryUnchecked(FunctionToTry function, P parameter) {
        try {
            return function.apply(parameter);
        } catch (RuntimeException re) {
            throw re;
        } catch (Exception e) {
            if (exType.isInstance(e)) {
                throw exConverter.apply(exType.cast(e));
            } else {
                throw new IllegalStateException("Unexpected checked exception", e);
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy