• 使用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");
    }
     
  • 相关阅读:
    JavaScript中Null和Undefined的区别
    javascript中的计算题
    数组去重
    javascript面向对象中继承实现的几种方式
    数列求值 题解
    首字母变大写 题解
    发工资咯:) 题解
    绝对值排序 题解
    数列有序 题解
    母牛的故事 题解
  • 原文地址:https://www.cnblogs.com/duan2/p/11778471.html
Copyright © 2020-2023  润新知