关于finally
finally关键字很多人都挺熟的吧,就简单讲一下吧。finally跟在try...catch结构之后,用于异常捕获后或者未捕获到的后续处理。即:在try中,无论异常有无发生,异常有无被catch到,finally都会执行。
关于try
值得注意的是,在try中,当一个语句发生异常的时候,其语句的后续所有语句都不执行(只是在try中)。
例如:
public int div(int i){
int result=0;
try{
result = a/i;
System.out.println("the try");
}
catch(ArithmeticException e){
System.out.println("the catch");
}
finally{
System.out.println("the finally");
}
System.out.println("the out");
return result;
}
当我们给 i赋值为0,给a赋值为一个正整数,执行这段代码的时候,第四行将发生除0异常。
所以第五行将不会被执行,异常被捕获到,所以catch块里面的代码会执行,其次是finally里的代码,最后是块后的代码。
程序输出如下:
the catch
the finally
the out
关于throws
我们知道,throws用于修饰一个方法,表示该方法会向类外抛出异常。
那么问题来了:throws可不可以跟try...catch...finally结构一起用呢?
答案是肯定的。因为谁能保证你catch中不会又发生新的异常呢。
throws只是起一个修饰的作用,并不一定会抛出异常,只表示可能会抛出异常。一般情况下,如果某个方法显式抛出异常,那么调用这个方法的另外一个方法就必须声明throws或者捕获异常,否则编译不通过。特殊情况,比如7/0,这里这个/号没法去定义它是一个方法,所以编译的时候如果不抛出异常或者不用try...catch,还是可以正常编译,只是我们在编程的时候就要注意。
例如这段代码:
package exception;
public class TestException {
public int a;
public TestException(int a){
this.a=a;
}
public int div(int i){
int result=0;
result = a/i;
System.out.println("the out");
return result;
}
}
---------------------------------------------------------------------
package exception;
public class TestMain {
public static void main(String[] args){
TestException t = new TestException(5);
try{
int i = t.div(0);
System.out.println("the second try");
}
catch(Exception e){
System.out.println("the second catch");
}
finally{
System.out.println("the second finally");
}
System.out.println("the second out");
}
}
---------------------------------------------------------------------
程序输出:
the second catch
the second finally
the second out
关于catch
catch,捕获异常。捕获,顾名思义,抓走了就没了,其块内的代码也只有在异常捕获到的时候才会执行。因此可以看到下面的代码:
package exception;
public class TestException {
public int a;
public TestException(int a){
this.a=a;
}
public int div(int i) throws ArithmeticException{
int result=0;
try{
result = a/i;
System.out.println("the try");
}
catch(ArithmeticException e){
System.out.println("the catch");
}
finally{
System.out.println("the finally");
}
System.out.println("the out");
return result;
}
}
package exception;
public class TestMain {
public static void main(String[] args){
TestException t = new TestException(5);
try{
int i = t.div(0);
System.out.println("the second try");
}
catch(Exception e){
System.out.println("the second catch");
}
finally{
System.out.println("the second finally");
}
System.out.println("the second out");
}
}
程序执行结果如下:
the catch
the finally
the out
the second try
the second finally
the second out