本文改編自http://blog.csdn.net/stellaah/article/details/6738424
[總結]
1.自定義異常: class 異常類名 extends Exception { public 異常類名(String msg) { super(msg); } } 2.標識可能拋出的異常: throws 異常類名1,異常類名2 3.捕獲異常: try{} catch(異常類名 y){} catch(異常類名 y){} 4.方法解釋: getMessage() //輸出異常的信息 printStackTrace() //輸出導致異常更為詳細的信息
[代碼]
1 // 自定義異常 2 class ZeroException extends Exception { 3 public ZeroException(String msg) { 4 super(msg); 5 } 6 } 7 8 class NegtiveException extends Exception { 9 public NegtiveException(String msg) { 10 super(msg); 11 } 12 } 13 // 自定義異常 End 14 15 16 17 class Calculate { 18 public int shang(int x, int y) throws ZeroException,NegtiveException { 19 if (y < 0) { 20 throw new NegtiveException("您輸入的是" + y + ",規定除數不能為負數!");// 拋出異常 21 } 22 if (y == 0) { 23 throw new ZeroException("您輸入的是" + y + ",除數不能為0!"); 24 } 25 26 int m = x / y; 27 return m; 28 } 29 } 30 31 // main 32 public class AppTest { 33 public static void main(String[] args) { 34 Calculate calculate = new Calculate(); 35 // 捕獲異常 36 try { 37 System.out.println("商=" + calculate.shang(1, -3)); 38 } catch (ZeroException e) { 39 System.out.println(e.getMessage()); 40 e.printStackTrace(); 41 } catch (NegtiveException e) { 42 System.out.println(e.getMessage()); 43 } 44 } 45 }