自定义Exception

本文改编自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 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值