문제

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?

도움이 되었습니까?

해결책 2

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

  }
}

다른 팁

This error indicates that UserException extends ProfileException

I'm quite convinced that UserException probably extends ProfileException. If you modified it, it's probable that the IDE did not compiled the latest version (for instance because compiler errors occured). Therefore you can run a clean and build command (available in most popular IDEs).

You can simply resolve the problem by swapping the catch blocks:

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

Most IDE's however will always write catch blocks from specific types toward more general types in order to prevent such dead code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top