JAVA---手动抛出异常

关于异常对象的产生:

  • 系统自动生成的对象
  • 手动的生成一个异常对象,并抛出(throw)
package exer;

public class StudentTest {
	public static void main(String[] args) {
		try {
			Student s=new Student();
			s.regist(-1111);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}
class Student{
	private int id;
	
	public void regist(int id) throws Exception{
		if(id>0){
			this.id=id;
		}else{
			throw new Exception("输入的数据非法!");
		}
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
}

posted @ 2022-02-22 11:24  ice--cream  阅读(236)  评论(0编辑  收藏  举报