Search code examples
exceptionjava-8custom-exceptions

Combining Multiple Exceptions in Custom Exception : Optimization


I have few similar methods and there calls as follows :

methodThrowingException() throws NullPointerException, InterruptedException, TimeoutException {
 <method logic>
}

Calling class :

 try{
    methodThrowingExceptions();
    <some other logic>
    }
    catch (NullPointerException npx) {
        npx.printStackTrace();
        log more details...
    }
    catch (InterruptedException inx) {
        inx.printStackTrace();
        log more details...
    }
    catch (TimeoutException tox) {
        tox.printStackTrace();
        log more details..
    }
  1. How (if) can I put all of these three in one Custom Exception?
  2. Other than (1) is there a way to optimise the code so that I need not write the entire same statements for multiple methods?

Solution

  • Since Java 7, you can use a multi-catch block:

    catch (NullPointerException | InterruptedException | TimeoutException e) {
        e.printStackTrace();
        log more details...
    }
    

    That said, you should never catch NullPointerException: that is a bug, and if it happens, the exception should bubble up. You can't reasonably expect a NPE to happen.

    In addition, doing the same thing for an InterruptedException as for the other exceptions is also very dubious. When catching an InterruptedException, you should reset the interrupted flag on the current thread, and stop what you're doing ASAP.