自定义异常

概述

程序开发中有时需要描述程序中特有的异常情况。为了解决这个问题,Java允许开发者自定义异常,但自定义的异常类必须继承自Exception或其子类。


自定义异常格式

//创建一个异常类继承Exception(或RuntimeException)
public class 自定义异常类名 extends Exception{
  //无参构造
  public 自定义异常类名(){
    super();//调用Exception的无参构造方法
  }
  //有参构造
  public 自定义异常类名(String message){
    super(message);//调用Exception的有参构造方法
  }
}

自定义异常类创建完成后,需要在满足条件时抛出异常的实例对象,定义格式如下:

  throw new 自定义异常类名(【参数列表】);

自定义异常使用案例

异常类代码演示:

public class OutOfBoundsException extends Exception{
    OutOfBoundsException(){
        super();
    }

    OutOfBoundsException(String str){
        super(str);
    }
}

创建一个有条件筛选并储存用户输入数据的方法:

    public static int validate(String str) throws NumberFormatException,OutOfBoundsException{
        int age = Integer.parseInt(str);
        if (age < 0 || age > 120)
            throw new OutOfBoundsException("超出范围");
        return age;
    }

测试类代码如下:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while(true){
            try {
                System.out.println("欢迎来到自我介绍APP");
                System.out.println("请输入姓名:");
                String name = input.nextLine();
                System.out.println("请输入年龄:");
                int age = validate(input.nextLine());
                System.out.println("你好,我是"+name+",今年"+age+"岁了");
            }catch (OutOfBoundsException  e){
                System.err.println(e.getMessage());
            }catch(NumberFormatException e){
                System.err.println("数据类型不匹配");
            }
        }
    }
posted on 2021-10-08 18:59  技术小伙伴  阅读(307)  评论(0)    收藏  举报