开发者

How do you check both the exception's type as well as they type of the nested exception?

Suppose I catch an exception that is of type AppException but I only want to carry out certain actions on that exception if it has a nested exception of type StreamException.

if (e instanceof AppException)
{
    // only handle exception if it contains a
    // nested exception of type 'St开发者_StackOverflow社区reamException'

How do I check for a nested StreamException?


Do: if (e instanceof AppException and e.getCause() instanceof StreamException).


Maybe instead of examining the cause you could try subclassing AppException for specific purposes.

eg.

class StreamException extends AppException {}

try {
    throw new StreamException();
} catch (StreamException e) {
   // treat specifically
} catch (AppException e) {
   // treat generically
   // This will not catch StreamException as it has already been handled 
   // by the previous catch statement.
}

You can find this pattern else where in java too. One is example IOException. It is the superclass for many different types of IOException, including, but not limited to EOFException, FileNotFoundException, and UnknownHostException.


if (e instanceof AppException) {
    boolean causedByStreamException = false;
    Exception currExp = e;
    while (currExp.getCause() != null){
        currExp = currExp.getCause();
        if (currExp instanceof StreamException){
            causedByStreamException = true;
            break;
        }
    }
    if (causedByStreamException){
       // Write your code here
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜