package exer; //手动的抛出一个异常的格式 public class MyException extends Exception{ static final long serialVersionUTD = -703489545; public MyException(){ } public MyException(String msg){ super(msg); } } package exer; public class TestStudent { public static void main(String[] args){ Student s=new Student(); try{ s.regist(-12); }catch(MyException e){ System.out.println(e.getMessage()); } System.out.println(s); } } class Student{ private int id; public void regist(int id) throws MyException{ if(id>0) this.id=id; else { throw new MyException("输入的学号有误"); } } public String toString() { return "Student [id=" + id + "]"; } }
时间: 2024-11-10 15:24:26