1 package p1.exception; 2 3 4 /* 5 * 异常处理的捕捉形式: 6 * 这是可以对异常进行针对性处理的方式. 7 * 8 * 具体格式是: 9 * try{ 10 * //需要被检测异常的代码 11 * } 12 * catch(异常类 变量){ //该变量用于接收发生的异常对象 13 * //处理异常的代码 14 * } 15 * finally{ 16 * //一定会被执行的代码 17 * } 18 */ 19 class FuShuIndexException extends RuntimeException /*Exception*/{//可以改继承运行异常,就不会报编译错误 20 public FuShuIndexException() { 21 // TODO Auto-generated constructor stub 22 } 23 24 FuShuIndexException(String msg){ 25 super(msg); 26 } 27 } 28 class Demo { 29 public static int method(int[] arr,int index) throws NullPointerException, FuShuIndexException { 30 31 if (arr == null) { 32 throw new NullPointerException("没有任何数组实体"); 33 } 34 if (index<0) { 35 throw new FuShuIndexException("角标变成负数了"); 36 } 37 return arr[index]; 38 } 39 40 } 41 42 public class ExceptionDemo4 { 43 44 public static void main(String[] args) { 45 46 int[] arr = new int[3]; 47 Demo d = new Demo(); 48 try { 49 // int num = d.method(arr,0); 50 int num = d.method(null,-30); 51 System.out.println("num="+num); 52 } catch (FuShuIndexException e) { 53 // TODO: handle exception 54 System.out.println("message:"+e.getMessage());//message:角标变成负数了 55 System.out.println("string:"+e/*.toString() 输出语句后输出都会变成字符串*/);//string:p1.exception.FuShuIndexException: 角标变成负数了 56 e.printStackTrace();//jvm默认的异常处理机制就是调用异常对象的该方法 57 System.out.println("负数角标异常"); 58 } catch (NullPointerException e) { 59 // TODO: handle exception 60 System.out.println(e.toString()); 61 }/*catch(Exception e) {//多catch时父类的catch放在最下面,否则编译失败 62 63 }*/ 64 65 66 System.out.println("over"); 67 68 } 69 70 } 71 /* 72 log4j log for (java; ;) { 73 74 } 75 */ExceptionDemo4