java自定义异常

 

/*
* 自定义异常类
* 1.继承于现有的异常结构:RuntimeException(运行时异常)、Exception
* 2.提供全局常量:serialVersionUID
* 3.提供重载的构造器
*/
public class MyException extends Exception{

  static final long serialVersionUID = -7034892390745766939L;

  public MyException() {
  }

  public MyException (String message) {
    super(message);
  }
}

// 测试

public class Demo {
  public static void main(String[] args) {
    try {
      Test1 t = new Test1();
      //t.us(12);
      t.us(-12);
      System.out.println(t.id);
    }catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

class Test1 {

  public int id;

  public void us(int id) throws MyException{
    if (id > 0) {
    this.id = id;
    }else {

    // 抛出自定义异常类
    throw new MyException("不能输入负数");
    }
  }
}

posted @ 2022-09-07 15:36  lai_xinghai  阅读(32)  评论(0)    收藏  举报