java自定义异常类

java自定义异常类

  1. MyException类

    //或者继承RuntimeException(运行时异常) 
    public class MyException extends Exception { 
    
      private static final long serialVersionUID = 1L; 
    
      // 提供无参数的构造方法
      public MyException() { 
      } 
    
      // 提供一个有参数的构造方法,可自动生成
      public MyException(String msg) { 
        super(msg);// 把参数传递给Throwable的带String参数的构造方法 
      } 
    
    } 
    

    查看Exception类的源码, 发现源码也就这么写的,继承后自定义的异常类也就成为了java异常体系的一部分

  2. 写一个Student类,手动抛出MyException

    class Student{
        private int id;
        // 该异常继承自Exception类,需要捕获或者向上抛出异常
        public void regist(int id) throws Exception {
            if ( id > 0){
                this.id = id;
            }else{
                // 手动抛出异常
                throw new MyException("不能输入负数");
            }
        }
    }
    
  3. 测试类StudentTest

    public class StudentTest{
        public static void main(String args[]){
            try{
                Student s = new Student();
                s.regist(-1001);
                // 对Student类throws的异常进行try-catch处理;
                System.out.println(s);
            }catch (Exception e){
                System.out.println(e.getMessage())
            }
        }
    }
    
posted @ 2019-05-13 20:30  HeliusKing  阅读(8087)  评论(0编辑  收藏  举报