异常
1 异常:程序运行中,异常出现,如果不进行合理处理,程序中断执行 2 3 异常全部处理完毕,就执行try-catch-finally,之后的语句 4 若是只catch部分异常,就不会执行try-catch-finally,之后的语句 5 6 先写异常的子类,再写异常的父类【先写小范围的异常,再写大范围的异常】 7 虽然直接捕捉Exception比较分方便,但是异常都是按照☉同样的一种方式☉进行处理 8 但是有些要求严格的项目,异常一定要分开处理 9 10 异常的处理 11 1.★try★,catch,finally 12 try...catch, try...catch(可以多个)...finally, try...finally 13 范例: 14 public class ExceptionDemo { 15 public static void main(String[] args) { 16 System.out.println("===========除法计算开始========="); 17 try { 18 int x = Integer.parseInt(args[0]); 19 int y= Integer.parseInt(args[1]); 20 System.out.println("除法计算:" + (x / y)); 21 【★只有一个catch,只能处理一个异常★ 22 如果存在其他没有处理的异常,依次会导致程序中断执行】 23 } catch (ArithmeticException ex) { 24 ex.printStackTrace();//打印完整的异常信息 25 } finally{ //不管异常是否catch处理完,都执行finally(除了一种情况,存在System.exits()) 26 System.out.println("##不管是否出现异常都执行!##"); 27 } 28 29 【★如果异常没有全部catch,那么这里就不会执行finally后面的代码!!!★】 30 System.out.println("===========除法结束============"); 31 } 32 } 33 34 2.throws[方法声明],当前方法出现异常后交给该方法被调用的地方进行处理 35 范例: 36 public class ThrowsDemo { 37 /** 38 * 由于存在throws,那么表示此方法里面产生的异常交给被调用处(如,main函数)处理 39 * @param x 40 * @param y 41 * @return 42 * @throws Exception 43 */ 44 public static int div(int x,int y)throws Exception{ 45 return x / y; 46 } 47 48 public static void main(String[] args){ 49 //处理方法div()里面的异常 50 try { 51 System.out.println(ThrowsDemo.div(10, 2)); 52 } catch (Exception e) { 53 e.printStackTrace(); 54 } 55 } 56 } 57 58 3.throw[自定义异常],手工抛出一个异常,并实例化异常 59 60 public class AddException extends Exception{ 61 public AddException(String msg){ 62 super(msg);//显示是自定义msg的内容,如果没有继承父类的带参构造方法,不显示msg内容 63 } 64 65 public static void main(String[] args){ 66 int num = 20; 67 try { 68 if (num > 10) { 69 throw new AddException("数值过大!");//自定义异常 70 } 71 } catch (Exception e) { 72 System.out.println("该程序结束"); 73 e.printStackTrace(); 74 } 75 } 76 } 77 78 Throwable 79 Error;Exception 80 RuntimeException;CheckedException 81 ArithmeticException,NullPointerException,NumberFormatException,ArrayIndexOutOfBoundsException;ClassCastException
82 Error: 此时的程序没执行,无论用户怎样处理,都处理不了
83 Exception: 程序运行时产生的异常,用户可以处理(后异常处理)
84 RuntimeException与CheckedException区别
86 CheckedException定义的异常◆必须◆被处理,而RuntimeException的异常可以★选择性处理★
87