I have a code logic as below:
// Option 1
try {
String result = x.getResult();
if (result == null) {
// some handling
logger.error("xxx");
}
} catch (Throwable t) {
// some handling
logger.error("xxx", t);
}
In the if and catch block, the handling and logging logic duplicates. We can change it to
// Option 2
try {
String result = x.getResult();
if (result == null) {
throw new RuntimeException("yyy");
}
} catch (Throwable t) {
// some handling
logger.error("xxx", t);
}
I feel creating an exception and then immediately catch it is just for code readability. However, this is an more expensive operation. Is option 2 better than option 1?
I wouldn't throw an exception just to streamline your code. How about merging them like this: