
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.说明
finally是异常处理语句结构的一部分,表示finally里面的代码块一定会执行。
2.使用注意
(1)finally不能单独使用,必须和try…语句或try…catch语句连用
(2)程序运行时,不论是否发生异常,finally代码块都会执行
(3)除非遇到System.exit方法,否则finally代码块一定会执行
3.实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class Demo2 {
public static void main(String[] args) {
try {
int i = 10/0;
System.out.println( "i=" +i);
} catch (ArithmeticException e) {
System.out.println( "Caught Exception" );
System.out.println( "e.getMessage(): " + e.getMessage());
System.out.println( "e.toString(): " + e.toString());
System.out.println( "e.printStackTrace():" );
e.printStackTrace();
} finally {
System.out.println( "run finally" );
}
}
}
|
运行结果:
1 2 3 4 5 6 7 | Caught Exception
e.getMessage(): / by zero
e.toString(): java.lang.ArithmeticException: / by zero
e.printStackTrace():
java.lang.ArithmeticException: / by zero
at Demo2.main(Demo2.java:6)
run finally
|
以上就就是java中finally处理异常的方法,在使用上结合了之前所学的try语句,运行代码我们会发现,finally部分的语句已经得到执行了。