I need make some code super stable and make sure all exceptions thrown within a block don't stop the code execution.
For now i have the following solution:
iterated.map(it -> {
try {
handleElement(it);
} catch (Exception e) {
handleError(e);
}
});
But from the other side i feel like there should be more elegant way to do it. Please help me to find it.
There is nothing wrong with you code and probably I would keep as is but if you like you can have a function that handles another function and catches the exceptions:
public class ExceptionCatcher<T, R> implements Function<T, R> {
public final Function<T, R> function;
public final Function<Exception, R> exceptionHandler;
public ExceptionCatcher(Function<T, R> function, Function<Exception, R> exceptionHandler) {
this.function = function;
this.exceptionHandler = exceptionHandler;
}
@Override
public R apply(T o) {
try {
return function.apply(o);
}catch (Exception e){
return exceptionHandler.apply(e);
}
}
};
and your code will look like:
ExceptionCatcher ex = new ExceptionCatcher(this::handleElement, this::handleError);
iterated.map(ex);
This is just an example; probably instead of a simple Consumer you want a BiFunction
and map to a default value based on the exception and on the failing onject. Or return null and filter null after this. It depends a lot on what you want to achieve
Well that's indeed how to call exceptions, but it's more important how to deal with these occurrences. An Exception should be thrown when the app experiences something which it could not expect. Just catching all exceptions will
Keep in mind what is a REAL exception for your app. Here are some examples:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.