码迷,mamicode.com
首页 > 其他好文 > 详细

自定义异常类

时间:2020-03-27 15:35:08      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:ring   ati   his   exception   sys   serial   sage   final   col   

自定义异常类

MyException

package com.aff.excep;

//自定义异常类:
//1.自定义的异常类继承现有的异常类
//2.提供一个序列号,提供几个重载的构造器
public class MyException extends RuntimeException {
    static final long serialVersionUID = -7034897190745766939L;
    public MyException() {
    }
    public MyException(String message) {
        super(message);
    }
}

 

testSud

package com.aff.excep;

import org.junit.Test;

public class testSud {
    @Test
    public void TestStudent() {
        Student s = new Student();
        try {
            s.regist(-17);
            System.out.println(s);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }

class Student {
    int id;
    public void regist(int id) {
        if (id > 0) {
            this.id = id;
        } else {
            throw new MyException("输入有误");
         }
     }
  }
}

输出结果:

输入有误

 

 

自定义异常类

标签:ring   ati   his   exception   sys   serial   sage   final   col   

原文地址:https://www.cnblogs.com/afangfang/p/12581763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!