finally总结:
finally代码块:定义一定执行的代码
通常用于关闭资源或者某些一定执行的代码
实例1:finally功能演示
class FuShuException extends Exception { FuShuException(String m) { super(m); } } class Demo { public int div(int x,int y) throws FuShuException { if(y<0) { throw new FuShuException("除数为负数"); } return x/y; } } class ExceptionDemo1 { public static void main(String args[]) { Demo d=new Demo(); try { int x=d.div(4,-1); System.out.println("x="+x); } catch(FuShuException e) { System.out.println(e.toString()); } finally { System.out.println("finally"); //finally存放的是一定会被执行的代码 } System.out.println("over"); } }
运行结果:
FuShuException: 除数为负数
finally
over
实例2:
1 class FuShuException extends Exception 2 { 3 FuShuException(String m) 4 { 5 super(m); 6 } 7 } 8 9 10 class Demo 11 { 12 public int div(int x,int y) throws FuShuException 13 { 14 if(y<0) 15 { 16 throw new FuShuException("除数为负数"); 17 } 18 return x/y; 19 } 20 } 21 22 23 class ExceptionDemo1 24 { 25 public static void main(String args[]) 26 { 27 Demo d=new Demo(); 28 try 29 { 30 int x=d.div(4,-1); 31 System.out.println("x="+x); 32 } 33 catch(FuShuException e) 34 { 35 System.out.println(e.toString()); 36 return; 37 } 38 finally 39 { 40 System.out.println("finally"); //finally存放的是一定会被执行的代码 41 } 42 System.out.println("over"); 43 } 44 }
运行结果:
FuShuException: 除数为负数
finally