• 自定义异常


    编写自己的异常类时需要记住下面的几点:

    • 所有异常都必须是 Throwable 的子类。
    • 如果希望写一个检查性异常类,则需要继承 Exception 类。
    • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。
    // 下面的代码是自定义一个异常类继承自Exception
    public class DivideByMinusException extends Exception{
        public DivideByMinusException (){
            super();          // 调用Exception无参的构造方法
        }
        public DivideByMinusException (String message){
            super(message); // 调用Exception有参的构造方法
        }
    }

    throw Exception  异常对象

    在下面的方法中判断被除数是否为负数,如果是负数,就使用throw关键字在方法中向调用者抛出自定义的异常对象

    public class Example26 {
        public static void main(String[] args) {
                int result = divide(4, -2);    // 调用divide()方法,传入一个负数作为被除数
                System.out.println(result);
        }
        //下面的方法实现了两个整数相除, 
        public static int divide(int x, int y) {
            if(y<0){ 
                throw new DivideByMinusException("被除数是负数");// 使用throw关键字声明异常对象
            }
            int result = x / y;   // 定义一个变量result记录两个数相除的结果
            return result;         // 将结果返回
        }
    }

    进行处理。

    public class Example27 {
        public static void main(String[] args) {
                  // 下面的代码定义了一个try…catch语句用于捕获异常
            try {
                int result = divide(4, -2);  // 调用divide()方法,传入一个负数作为被除数
                System.out.println(result);
            } catch (DivideByMinusException e) {     // 对捕获到的异常进行处理
                System.out.println(e.getMessage()); // 打印捕获的异常信息
            }
        }
        // 下面的方法实现了两个整数相除,并使用throws关键字声明抛出自定义异常
        public static int divide(int x, int y) throws DivideByMinusException {
            if (y < 0) {
                throw new DivideByMinusException("被除数是负数");// 使用throw关键字声明异常对象
            }
            int result = x / y;     // 定义一个变量result记录两个数相除的结果
            return result;           // 将结果返回
        }
    }

    运行结果:

  • 相关阅读:
    WHU 1572 Cyy and Fzz (AC自动机 dp )
    Codeforces 441D Valera and Swaps(置换群)
    Codeforces 527E Data Center Drama(欧拉回路)
    差分约束小结
    Codeforces 193D Two Segments 解题报告
    SGU 231.Prime Sum
    SGU 249.Matrix(Gray码)
    SGU 222.Little Rooks
    SGU 207.Robbers
    risc-v的寻址模式
  • 原文地址:https://www.cnblogs.com/thiaoqueen/p/8482350.html
Copyright © 2020-2023  润新知