2015-05-18 55 views
1

我想知道如何處理「包含」異常。因爲這個術語不夠具體,讓我舉一個PrivilegedActionException的例子。處理包含異常

簡而言之,此例外將在其cause中包含PrivilegedAction內計算過程中拋出的任何檢查異常。

現在如果我有和方法computate() throws IOException我 - 如果對自己執行 - 把它處理:因爲這已經PriviledgedAction我得到的唯一的例外是PrivilegedActionException被執行

try { 
    computate(); 
} catch (FileNotFoundException ex) { 
// Handle file not found 
} catch (SomeOtherSubtypeOfIOException ex) { 
// handle that again 
} 

現在:

try { 
    Subject.doAs(() -> computate()); 
} catch (PrivilegedActionException ex) { 
    // Now what? 
} 

我可以通過調用ex.getCause()從前面的示例中獲得IOException,但是看起來如何?顯而易見的方式看起來很奇怪...

catch (PrivilegedActionException ex) { 
    if (ex.getCause() instanceof FileNotFoundException.class) { 
    // handle FileNotFound 
    } else if (ex.getCause() instanceof xxx) { 
    // something else 
    } 
} 
+0

這看起來幾乎相同,但更好地解釋:http://stackoverflow.com/questions/10437890/what-is-the-best-way-to-handle-an-executionexception –

回答

0

你可以得到原因,並重新扔它。然後用外部try-catch處理異常。

catch (PrivilegedActionException ex) { 
    Throwable cause = ex.getCause(); 
    if(cause !=null) throw ex.getCause(); 
    else ex.printStackTrace(); 
}