设定
所以我有两个例外:
ProfileException extends Exception
UserException extends Exception
我的帮助程序类方法之一将这两个异常抛出:
Long getSomething() throes ProfileException, UserException
我在这样的try catch块中调用此方法。
try
{
Long result = helperObj.getSomething();
}
catch(ProfileException pEx)
{
//Handle profile exception
}
catch(UserException uEx)
{
//Handle user exception
}
题
现在,我需要区分方法抛出的两个异常,并根据所抛出异常的类型分别处理异常。
但是我得到以下错误。
Unreachable catch block for UserException. It is already handled by the catch block for ProfileException.
如何根据该getSomething()方法引发的异常类型分别进行区分和处理?
最佳答案
由于这两个异常都在层次结构中处于同一级别,因此您必须像下面这样使用
try {
Long result = helperObj.getSomething();
}
catch(Exception ex) {
if (ex instanceOf ProfileException) {
//Handle profile exception
} else if (ex instanceOf UserException) {
// Handle user exception
}
}