自定义异常——《Thinking in Java》随笔026
1 //: Inheriting.java 2 package cn.skyfffire; 3 /** 4 * 自定义异常 5 * 6 * user: skyfffire 7 * time: 下午4:04:58 8 */ 9 class MyException extends Exception { 10 private static final long 11 serialVersionUID = -7818673878626777238L; 12 public MyException(){} 13 14 public MyException(String msg) { 15 super(msg); 16 } 17 } 18 19 public class Inheriting { 20 // 方法f选择不带参数的构造器初始化自定义异常 21 public static void f() throws MyException { 22 System.err.println("Throwing MyException from f():"); 23 24 throw new MyException(); 25 } 26 27 // 方法g选择带参数的构造器初始化自定义异常, 说明异常来源 28 public static void g() throws MyException { 29 System.err.println("Throwing MyException form g()"); 30 31 throw new MyException("Originated in g()"); 32 } 33 34 public static void main(String[] args) { 35 try { 36 f(); 37 } catch (MyException e) { 38 e.printStackTrace(); 39 } 40 41 // MyException是‘可继续异常’ 42 // 所以在调用f方法抓住异常时, 也可以在此时再次执行g方法 43 try { 44 g(); 45 } catch (MyException e) { 46 e.printStackTrace(); 47 } 48 } 49 } 50 51 ///:~