zoukankan      html  css  js  c++  java
  • 36 异常

    例子:

    package com.snape.java.ExceptionProj;
    
    import java.util.Scanner;
    
    public class HotelTryCatchDemo {
        public static void main(String[] args) {
            try {
                AgeTest();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }//main方法结束
    
        /**
         * throw 抛出异常对象的处理方案:
         * 1.通过try...catch包含throw语句,自己抛自己处理
         * 2.通过throws在方法声明处抛出异常类型--谁调用谁处理--调用者可以自己处理,也可以继续上抛
         *   此时可以抛出与throw对象相同的类型或者其父类
         */
        //描述酒店入住规则,年龄在18岁以下或80岁以上,须由亲友陪同
    //    public static void AgeTest(){
    //        try {
    //            Scanner input = new Scanner(System.in);
    //            System.out.println("请输入年龄:");
    //            int age = input.nextInt();
    //
    //            if(age<18 || age>80){
    //                throw new Exception("年龄在18岁以下或80岁以上,须由亲友陪同");
    //            }else{
    //                System.out.println("欢迎来到本酒店");
    //            }
    //        }catch (Exception e){
    //            e.printStackTrace();
    //        }
    //    }//AgeTest()方法结束
    
    
        public static void AgeTest() throws Exception {
            Scanner input = new Scanner(System.in);
            System.out.println("请输入年龄:");
            int age = input.nextInt();
    
            if(age<18 || age>80){
                throw new Exception("年龄在18岁以下或80岁以上,须由亲友陪同");
            }else{
                System.out.println("欢迎来到本酒店");
            }
        }//AgeTest()方法结束
    }//类HotelTryTest类结束

    结果:

  • 相关阅读:
    ZOJ Problem Set–2781 Rounders
    ZOJ Problem Set 3418 Binary Number
    ZOJ Problem Set 1090 The Circumference of the Circle
    ZOJ Problem Set 2932 The Seven Percent Solution
    java的反射应用
    C++指针之数据成员指针
    为了实现相同账号不能重复登录功能做的努力
    我对设计模式的理解
    ZOJ Problem Set – 1045 HangOver
    好久不见
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/12182257.html
Copyright © 2011-2022 走看看