Java异常——自定义异常、异常链
1. 自定义异常概述
(1) 使用Java内置的异常类可以描述在变成时出现的大部分异常情况;
(2) 也可以通过自定义异常描述特定业务产生的异常类型;
(3) 所谓自定义异常,就是定义一个类,去继承Throwable类或者它的子类。
2. 案例
public class HotelAgeException extends Exception {
public HotelAgeException(){
super("18岁以下,80岁以上的住客必须由亲友陪同");
}
}
public static void testAge() throws HotelAgeException {
System.out.println("请输入年龄:");
Scanner input = new Scanner(System.in);
int age = input.nextInt();
if (age < 18 || age > 80) {
throw new HotelAgeException();
} else {
System.out.println("欢迎入住本酒店");
}
}
public static void main(String[] args) {
try {
testAge();
} catch (HotelAgeException e) {
System.out.println(e.getMessage());
System.out.println("酒店前台工作人员不允许办理入住登记");
}catch(Exception e){
e.printStackTrace();
}
}
3. 异常链
有时候我们会捕获一个异常后再抛出另一个异常
案例:
public class TryDemoFive {
public static void main(String[] args) {
try {
testThree();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testOne() throws HotelAgeException {
throw new HotelAgeException();
}
public static void testTwo() throws Exception {
try {
testOne();
} catch (HotelAgeException e) {
throw new Exception("我是新产生的异常1",e);
}
}
public static void testThree() throws Exception {
try {
testTwo();
} catch (Exception e) {
Exception e1=new Exception("我是新产生的异常2");
e1.initCause(e);
throw e1;
}
}
}