今天来分析下java 中Exception的处理方式,我们都知道,它执行的顺序如下:
[b]1. try:检查是否有异常发生;
2. 如果有,则由catch来捕获;
3. 不管是否有异常发生,都会进入到finally里执行。[/b]
先记住下面的结论:
[b]1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。[/b]
例1.
输出结果:
例2.
输出结果:
例3.
输出结果:
[b]1. try:检查是否有异常发生;
2. 如果有,则由catch来捕获;
3. 不管是否有异常发生,都会进入到finally里执行。[/b]
先记住下面的结论:
[b]1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。[/b]
例1.
public class Demo {
public static int doexception(){
try{
return 1;
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}
输出结果:
finally ....
return value:1
例2.
public class Demo {
public static int doexception(){
try{
throw new Exception("aaa");
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}
输出结果:
catch exception
finally ....
return value:0
例3.
public class Demo {
public static int doexception(){
try{
throw new Exception("aaa");
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
return 1;
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}
输出结果:
catch exception
finally ....
return value:1