Search code examples
javaexceptionunreachable-code

Unreacheable Catch Block Issue


Setup

So I have two exceptions:

ProfileException extends Exception
UserException extends Exception

One of my helper class method throws these two exceptions togeather:

  Long getSomething() throes ProfileException, UserException

I invoke this method inside a try catch block like this.

try
{
   Long result = helperObj.getSomething();
}
catch(ProfileException pEx)
{
//Handle profile exception
}
catch(UserException uEx)
{
//Handle user exception
}

Question

  1. Now I NEED to necessarily distinguish between those two exceptions thrown by the method and handle the exceptions separately depending on the type of exception being thrown.

However I get the following error.

Unreachable catch block for UserException. It is already handled by the catch block for ProfileException.

How can I distinguish and handle seperately depending on the type of exception thrown by that getSomething() method?


Solution

  • Since both exceptions are in the same level in the heirarchy, you have to use like following

    try {
       Long result = helperObj.getSomething();
    }
    catch(Exception ex) {
      if (ex instanceOf ProfileException) {
          //Handle profile exception
    
      } else if (ex instanceOf UserException) {
         // Handle user exception
    
      }
    }