I often write something like this in my code:
try {
obj.doSomething();
} catch (Throwable exception) {
// there is no need to interrupt application
String exceptionMessage = String.valueOf(exception.getMessage());
Log.e("Name of my app", exceptionMessage, exception);
// and may be something else
}
So I wrote this simple class:
public class TryHelper {
public static final TryHelper LOGGER = new TryHelper(new Handler<Throwable>() {
@Override
public void handle(Throwable exception) {
LogUtils.exception(exception);
}
});
private final Handler<Throwable> exceptionHandler;
public TryHelper(Handler<Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
public void tryDoIt(Runnable runnable) {
try {
runnable.run();
} catch (Throwable exception) {
exceptionHandler.handle(exception);
}
}
public void tryDoIt(RunnableAbleToThrowCheckedException runnable) {
try {
runnable.run();
} catch (Throwable exception) {
exceptionHandler.handle(exception);
}
}
}
And interfaces from my own util
package:
public interface RunnableAbleToThrowCheckedException {
void run() throws Exception;
}
public interface Handler<T> {
void handle(T obj);
}
Using:
TryHelper.LOGGER.tryDoIt(new Runnable() {
@Override
public void run() {
obj.doSomething();
}
});
But I'm pretty bad at English. So I need your help in choosing proper names (instead of
TryHelper
,RunnableAbleToThrowCheckedException
,tryDoIt()
, etc.).I'm a fan of Uncle Bob and his book "Clean Code":
We want the code to read like a top-down narrative.
And what do you think about the need for this class? Maybe it was a bad idea?