zoukankan      html  css  js  c++  java
  • 使用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");
    }
     
  • 相关阅读:
    BZOJ2456: mode 众数卡空间
    BZOJ4128: Matrix 矩阵BSGS
    [SDOI2011]计算器 BSGS
    前台中文搜索到后台乱码
    批量删除实现js+springmvc
    基于Jquery+Ajax+Json实现分页显示
    分页条的制作
    input text中不能显示空格后的内容
    mysql存入中文乱码问题
    WEBROOT根目录 <%=request.getContextPath()%>
  • 原文地址:https://www.cnblogs.com/duan2/p/11778471.html
Copyright © 2011-2022 走看看