异常知识点:

 

 
  
  1. 错误: 
  2. Throwable  可抛出 
  3.    | 
  4.    | 
  5.    ----Error   不可恢复 
  6.    | 
  7.    | 
  8.    ----Exception   经过处理后可以继续运行 
  9.          | 
  10.          | 
  11.          ----CheckedException 
  12.          | 
  13.          | 
  14.          ----RuntimeException 
  15.  
  16. 运行时异常:通过合法性判断可以排除此类问题 
  17. 检查异常:  语法强制必须try catch,提高代码健壮性。 
  18.        
  19.  
  20. 常见的异常 
  21. NullpointException                      使用没有初始化的引用类型对象 
  22. ArrayIndexOutOfBoundsException          数组下标不合法 
  23. IndexOutOfBoundsException               集合索引错误 
  24. StringIndexOutOfBoundsException         字符串索引错误 
  25. ArithmeticException                     除数为0 
  26.  
  27.  
  28. 父类子类方法重写中,异常要注意: 
  29. 1) 子类方法抛出的异常范围不能超出父类方法 
  30. 2) 子类方法抛出异常的个数不能大于父类 
  31. 3) 子类方法可以不抛出异常 

建个自定义异常类,继承和重写 

 
  
  1. public class DivideException extends Exception 
  2.  
  3.     public DivideException() 
  4.     { 
  5.          
  6.     } 
  7.     public DivideException(String message)//重写方法Exception(String message) 
  8.     { 
  9.         super(message); 
  10.     } 
  11.  

 

方法throws自定义异常

 

 
  
  1. public class Divide 
  2.     public static void main(String[] args) 
  3.     { 
  4.         Divide d = new Divide(); 
  5.          
  6.         try 
  7.         { 
  8.             d.divide(50); 
  9.         } 
  10.         catch (DivideException e) 
  11.         { 
  12.             e.printStackTrace(); 
  13.         } 
  14.          
  15.     } 
  16.      
  17.     public double divide(int i, int j) throws DivideException //方法throws异常 
  18.     { 
  19.         if (j == 0
  20.         { 
  21.             throw new DivideException("除数不能为0!");//异常时throw提示语句 
  22.         } 
  23.         else 
  24.         { 
  25.             double k = i / j; 
  26.             return k; 
  27.         } 
  28.          
  29.     }