自定义异常类
- 使用Java内置的异常类可以描述在编程时出现的大部分异常情况
- 也可以通过自定义异常描述特定业务产生的异常类型
- 所谓自定义异常,就是定义一个类,去继承 Throwble 类或者它的子类
- 例:
public class HotelAgeException extends Exception {
public HotelAgeException(){
super("18岁以下,80岁以上的住客必须由亲友陪同");
}
}
public class TryDemoFour {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
testAge();
} catch (HotelAgeException e) {
System.out.println(e.getMessage());
System.out.println("酒店前台工作人员不允许办理入住登记");
}catch(Exception e){
e.printStackTrace();
}
}
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 ArithmeticException();
//throw new Exception("18岁以下,80岁以上的住客必须由亲友陪同");
throw new HotelAgeException();
} else {
System.out.println("欢迎入住本酒店");
}
}
}
2139

被折叠的 条评论
为什么被折叠?



