2015-05-18 54 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(); 
}