请问一下,我好想听过只要catch到exception后,就执行catch块里面的东西
来源:百度知道 编辑:UC知道 时间:2024/06/06 12:24:31
public static void main(String[] args) {
try {
Class.forName("AA");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
System.out.println("first。。。。");
}
System.out.println("two。。。。。");
}
,谢谢
上面抛出异常后,底下两句话都可以输出的啊?
我的意思是,即使不用finally,catch到异常后,接下来的代码不是还是会执行吗,比如上面的
都会执行的,那是因为你已经捕捉到异常了,如果你直接将异常抛给上层代码的话就不会执行下面的代码了,比如说将上面的代码改为
public static void main(String[] args) throws ClassNotFoundException{
Class.forName("AA");
System.out.println("two。。。。。");
}
下面的那段代码就不会执行了,因为出现了异常,程序自己不能解决,而交给了上层去了。你写的那个因为你已经将异常捕捉到了,并做了处理。当然程序会继续往下执行了。
希望以上讲解会对你有所帮助
如果你这么写的话:
public static void main(String[] args) {
try {
Class.forName("AA");
System.out.println("three。。。。。");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
System.out.println("first。。。。");
}
System.out.println("two。。。。。");
}
执行到catch以后,System.out.println("three。。。。。");这句话是不会执行的,而下面两句
System.out.println("first。。。。");
System.out.println("two。。。。。");
会执行
try
catch
finally
这是一个结构,先try,如果某一句出错就执行catch,但是始终会执行finally