throw exception and then catch vs duplicate error handling

69 Views Asked by At

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?

2

There are 2 best solutions below

2
shmosel On

I wouldn't throw an exception just to streamline your code. How about merging them like this:

String result = null;
try {
    result = x.getResult();
} catch (Throwable t) {
    // fall through
}
if (result == null) {
    // some handling
    logger.error("xxx", t);
}
1
Enrique Marin On
 try {
        String result = x.getResult();
      /*  if (result == null) { < -- Code not need it
            throw new RuntimeException("yyy");
        }*/
    } catch (Throwable t) {
        // some handling
        logger.error("xxx", t);
    }

yeah 2 option is better, less duplicate code that is all. U can remove the if sentence and then be sure on the catch u have the Exception type that u are expecting. If not then use Throwable.

https://www.youtube.com/watch?v=PzK4ZXa2Tbc <-- check this