手动抛出异常

throw(注意不是throws)

例如:

throw new RuntimeException("您输入的数据非法"); //运行时异常,可以不用处理

throw new Exception("您输入的数据非法"); //全局异常,需要处理 

下面举个例子

public class StudentTest{

  public static void main(String[] args){

    try{

      Student s = new Student( ) ;

      s.regist(-1001);

      System.out.println(e.getMessage( ) ); //此处的Message 就是手动抛出的异常 即“你输入的数据非法”

      }

  }

}

 

class Student{

  private int id ;

  public void regist (int id) throws Exception{

    if(id>0){

      this.id = id ;

    }else{

      throw new Exception("你输入的数据非法") ;

      }

}      

posted @ 2022-11-05 18:47  平凡的柳先生  阅读(69)  评论(0)    收藏  举报