本文改编自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 }
时间: 2024-10-24 02:42:36