说到Java异常处理,大家肯定想到了try、catch、finally,执行顺序是按上述顺序,catch和finally是可选块,但两者必须有一个出现,finally这个块中JVM将进行资源回收。我们都知道,执行了return之后就意味着一个方法或模块的结束,那么,如果是如下代码,将如何执行呢?
public class Test {
public static void main(String[] args){
System.out.println("The method return "+value());
}
public static int value(){
int i = 0;
try{
System.out.println("This is try block , and i = "+i);
i = 1;
return i;
}catch(Exception e){
System.out.println("This is catch block , and i = "+i);
i = 2;
return i;
}finally{
System.out.println("This is finally block , and i = "+i);
i = 3;
return i;
}
}
}
返回结果:
This is try block , and i = 0
This is finally block , and i = 1
The method return 3
如果我们尝试把finally模块的return语句注释掉,则会打印如下结果:
This is try block , and i = 0
This is finally block , and i = 1
The method return 1
这个告诉我们,无论在异常模块中怎样return,只会结束该模块,程序仍然继续执行其他模块。
因此,执行顺序如下:try模块---->是否有异常抛出:有------>catch模块------>finally模块;没有----->finally模块。
*************************************Java7中的异常改进********************************************
1.Java7引入了多异常抛出,改进了以往一个try配十几个catch块的荒谬局面,如:
catch(IndexOutOfBoundsException|NullPointerException|IllegalArgumentException|NumberFormatException e){}
2.Java7的try关键字增加了圆括号声明、初始化资源,在执行完try模块之后,try语句会自动关闭这些资源,避免了以前必须在Finally块中关闭资源。
3.Java7对throw语句进行了加强,即使一个异常声明为Exception,但如果该Exception类型为其他子类弄的话,throw抛出的异常是最精确的子类异常。
**注意**:子类抛出的异常必须小于父类抛出异常。