2011-06-25 105 views
18

假設我發現類型爲AppException的異常,但我只想對該異常執行某些操作,前提是它的嵌套異常類型爲StreamException如何檢查異常的類型以及嵌套異常的類型?

if (e instanceof AppException) 
{ 
    // only handle exception if it contains a 
    // nested exception of type 'StreamException' 

如何檢查嵌套StreamException

回答

19

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

1
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 
    } 
} 
+1

也許它會更容易使用Apache公共庫的ExceptionUtils.indexOfType(e,StreamException.class)!= -1。 – atott

5

也許代替檢查原因,您可以嘗試爲特定目的子類化AppException。

例如。

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. 
} 

你可以在java中找到這個模式。一個例子是IOException。它是許多不同類型IOException的超類,包括但不限於EOFException,FileNotFoundException和UnknownHostException。