第八章java异常处理 课后习题 ,不知道怎么抛出一个自定义异常
定义一个类继承Expection,定一个public方法,用抓取异常的方法抛出就好了呀
package com.demo4;
/**
* @Author blackoon88
* @Date 2022/5/19
*/
public class Customer {
private int age;
public void setAge(int age) throws MyException {
if(age<0||age>100){
throw new MyException("输入年龄范围在1~100之间");
}
this.age = age;
}
public static void main(String[] args) {
try {
Customer customer = new Customer();
customer.setAge(1000);
}catch (MyException e){
System.out.println(e.getMessage());
}
}
}
package com.demo4;
/**
* @Author blackoon88
* @Date 2022/5/19
*/
public class MyException extends Exception{
String message;
public MyException(String ErrorMessage){
this.message = ErrorMessage;
}
@Override
public String getMessage() {
return message;
}
}
若有帮助,谢谢采纳~
以下仅供参考
setAge(int age){
.......
if (!age<100 & age>0){try(
//抛出异常
)
catch
{
//捕获异常
}
}
}