【问题标题】:Why Custom exception class is needed [duplicate]为什么需要自定义异常类[重复]
【发布时间】:2019-11-12 02:22:46
【问题描述】:

在自定义异常类中我们调用超类(Exception class)的构造函数。为什么不直接调用Exception类构造函数而不是自定义类构造函数呢?请在下面找到示例

class InvalidAgeException extends Exception {
    InvalidAgeException(String s) {
        super(s);
    }
}

class TestCustomException1 {

    static void validate(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("not valid");
        }
        else {
            System.out.println("welcome to vote");
        }
    }

    public static void main(String args[]){  
        try {  
            validate(13);  
        }
        catch (Exception m) {
            System.out.println("Exception occured: " + m);
        }
        System.out.println("rest of the code...");
    }
}

在上面的例子中我们可以使用 throw new Exception("not valid"); 那么这里自定义异常类有什么用呢?

【问题讨论】:

  • 使用throw new Exception("not valid"); - 在阅读日志时您怎么知道它应该是InvalidAgeException

标签: java exception


【解决方案1】:

因为它让调用代码可以更好地控制它需要关心的异常。在这种情况下,main 仅捕获基类 Exception,但如果将来有人添加一个关心无效年龄而不关心其他类型异常的方法怎么办?

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2011-05-31
    • 2012-11-25
    • 2011-12-02
    • 2015-08-16
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多