使用throw和throws 引发异常

1.throw 用在方法内抛出异常,通常可以自行使用try catch进行异常处理

如果不自行处理的话,需要在方法上使用throws抛出异常

 1   public static void testAge(){
 2         System.out.println("请输入年龄:");
 3         Scanner input =new Scanner(System.in);
 4         int age=input.nextInt();
 5         try {
 6             if (age<18||age>80){
 7                 throw new Exception("18岁一下,80岁以上的住客必须陪同");
 8             }else {
 9                 System.out.println("欢迎光临本酒店");
10             }
11         }catch (Exception e){
12             log.error("年龄异常");
13         }
14     }


调用方法处理一场

public static void main(String[] args) {
try {
testAge();
} catch (Exception e) {
e.printStackTrace();
log.error("年龄异常");
}
}
public static void testAge() throws Exception{
System.out.println("请输入年龄:");
Scanner input =new Scanner(System.in);
int age=input.nextInt();
if (age<18||age>80){
throw new Exception("18岁一下,80岁以上的住客必须陪同");
}else {
System.out.println("欢迎光临本酒店");
}
}


抛出运行时异常
抛出运行时异场,不需要处理,但是程序或中断运行
public static void testAge(){
System.out.println("请输入年龄:");
Scanner input =new Scanner(System.in);1
int age=input.nextInt();
if (age<18||age>80){
throw new RuntimeException("18岁一下,80岁以上的住客必须陪同");
}else {
System.out.println("欢迎光临本酒店");
}
System.out.println("iver");
}
 

猜你喜欢

转载自www.cnblogs.com/duan2/p/11778471.html