异常处理是为了保证程序出现了异常的时候,及时地去捕获到异常,并使程序继续处理的手段。
常用的写法是
try{
}catch(Exception e){
}finally{
}
try块是可能抛出异常的代码块,catch块是处理try块中抛出的异常用的。可以有一个或者多个catch块。
finally块是最后的处理块。不管try是否抛出异常,也不管catch是否捕获到了抛出的异常,该段代码总会运行。
try块后面可以有catch或者finally块,或者catch和finally块都有。但是不能catch和finally块都没有。
程序流程
当try块的代码没有异常抛出的时候,try块执行完毕之后,程序会顺序执行finally块的代码。
当有异常抛出的时候,后续的一个或者多个catch的定义中,应该有一个最先匹配到的异常来处理捕获到的异常,然后程序在进入finally代码块。
如果程序没有定义catch块或者catch块代码不能捕获到程序的异常,如果有finally代码块,程序也是先执行finally代码块,然后再异常退出流程。如果finally代码块后面还有代码,则这些代码不会被执行。
代码举例A:
代码的目的:原本是想让代码执行两遍,实际上,因为有异常抛出,所以程序不能执行两遍。
public class TryTestA {
public static void main(String[] args){
System.out.println("===TryTestA===");
for(int x = 0; x < 2; x++){
try{
System.out.println("this is try block before exception");
System.out.println(10/0);
System.out.println("this is try block after exception");
}finally{
System.out.println("this is finally block");
}
System.out.println("this is other block afer finally block. x is "+x);
}
}
}
代码的结果为:
===TryTestA===
this is try block before exception
this is finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.baby.TryTestA.main(TryTestA.java:9)
结果说明:
程序的目的是将try块执行两遍,但是因为抛出了异常,程序并没有捕获到异常,所以,执行了一遍就退出了。在退出之前,程序执行了finally里面的代码。
代码举例B:
代码的目的:让代码执行两遍来测试程序的流程
public class TryTestB {
public static void main(String[] args) throws ArithmeticException {
System.out.println("===TryTestB===");
for (int x = 0; x < 2; x++) {
try {
System.out.println("this is try block before exception");
System.out.println(10 / 0);
System.out.println("this is try block after exception");
} catch (ArithmeticException e) {
System.out.println("this is catch(ArithmeticException e) block");
} catch (Exception e) {
System.out.println("this is catch(Exception e) block");
} finally {
System.out.println("this is finally block");
}
System.out.println("this is other block afer finally block. x is " + x);
}
}
}
代码的结果为:
===TryTestB===
this is try block before exception
this is catch(ArithmeticException e) block
this is finally block
this is other block afer finally block. x is 0
this is try block before exception
this is catch(ArithmeticException e) block
this is finally block
this is other block afer finally block. x is 1
结果说明:
在try块抛出的异常,被catch捕获到,然后程序继续向下处理。整个流程一共处理了两遍。符合预期。