java 中
try {throw1...}catch {throw2...}finally{throw3...},
请帮忙解释一下上述简易代码如何执行
先程序跑try{ xxxx}代码,如果有错误就继续跑catch{xxx}里代码,然后执行finally{xxxx}里代码。如果try里没有错误,就直接在执行finally里代码了。finally无论程序是否报错都会执行的。
好问题
finally的代码无论如何都会执行
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
try
{
foo();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
public static void foo() throws java.lang.Exception
{
try
{
throw new Exception("1");
}
catch (Exception ex)
{
throw new Exception("2");
}
finally
{
throw new Exception("3");
}
}
}
结果
java.lang.Exception: 3
显然1肯定执行了,不然不会触发3
但是主程序抓到的是最后一个异常,所以是3