自定义异常throw

时间:2023-03-09 18:13:09
自定义异常throw

简单自定义一个年龄小于等于0,或者大于120会出现的异常

首先继承父类Exception,调用父类的构造器,这样才可以报出自己想要的异常

public class AgeException extends Exception {

    /**
*
*/
private static final long serialVersionUID = 1L; public AgeException(String message) {
super(message);
} }

然后进行小小的测试

 package com.lianxi.zidingyichang;

 public class Test {
private int age; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public void ageException(int age) throws AgeException {
if (age > 0 && age <= 120) {
this.age = age;
System.out.println("格式正确");
} else {
//抛出自己自定义异常
AgeException exception = new AgeException("请输入正确年龄");
throw exception;
}
} public static void main(String[] args) {
Test test = new Test();
try {
test.ageException(120);
} catch (AgeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }