finally代码块:定义一定执行的代码
通常用于关闭资源
finally只有一种情况不执行,就是执行了System.exit(0)的时候,是系统退出,JVM结束
1 class NegativaException extends Exception 2 { 3 NegativaException(String msg) 4 { 5 super(msg); 6 } 7 } 8 class Demo 9 { 10 int div(int a,int b)throws NegativaException 11 { 12 if(b < 0) 13 { 14 throw new NegativaException("出现负数"); 15 } 16 return a/b; 17 } 18 } 19 class ExceptionDemo 20 { 21 public static void main(String[] args) 22 { 23 Demo d = new Demo(); 24 25 try 26 { 27 int x = d.div(4,-1); 28 System.out.println("x="+x); 29 } 30 catch(NegativaException e) 31 { 32 System.out.println(e.toString()); 33 return; 34 } 35 finally 36 { 37 System.out.println("finally");//finally中存放的是一定会被执行的代码 38 } 39 40 System.out.println("Over"); 41 } 42 }
Happy coder