自定义异常类

自定义异常类

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("输入有误");
         }
     }
  }
}

输出结果:

输入有误

 
All that work will definitely pay off
原文地址:https://www.cnblogs.com/afangfang/p/12581763.html