jax*_*jax 132 java exception-handling
在这个代码中,someVar即使执行catch块并抛出第二个异常,也会设置代码?
public void someFunction() throws Exception {
try {
//CODE HERE
} catch (Exception e) {
Log.e(TAG, "", e);
throw new Exception(e);
} finally {
this.someVar= true;
}
}
Run Code Online (Sandbox Code Playgroud)
Gar*_*ryF 172
是的,finally块总是运行...除非:
System.exit(0);此外,如果finally块中的方法抛出未捕获的异常,则之后不会执行任何操作(即异常将像在任何其他代码中一样抛出).发生这种情况的一个非常常见的情况是java.sql.Connection.close().
顺便说一句,我猜你所使用的代码示例仅仅是一个例子,但要小心将实际逻辑放在finally块中.finally块用于资源清理(关闭数据库连接,释放文件句柄等),而不是必须运行的逻辑.如果必须在try-catch块之前运行它,远离可能抛出异常的东西,因为你的意图几乎肯定在功能上是相同的.
小智 5
最后,块总是执行。
public class ExceptionTest {
public static void someFunction(String input) throws Exception {
try {
if( input.equals("ABC") ) {
System.out.println("Matched");
}
} catch (Exception e) {
throw new Exception(e);
} finally {
System.out.println("Input Is "+input+" Finally Executed!!!");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("********* Test with VALUE ********* ");
someFunction("ABC");
System.out.println("\r\n********* Test with NULL ********* ");
someFunction(null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
64914 次 |
| 最近记录: |