java - 编译错误: unreported exception Add; must be caught or declared to be thrown

标签 java exception throw

我想通过添加创建用户定义的异常,但出现编译错误。

class Test{

    public static void main(String[] args){

        int a=9, b=67, result;
        result = a+b;
        throw new Add("Addition has been performed");
    }
}
class Add extends Throwable{
    Add(){
        printStackTrace();
    }
    Add(String message){
        System.out.println(message);
        printStackTrace();  
    }
}

错误是:

Practice.java:8: error: unreported exception Add; must be caught or declared to be thrown
                throw new Add("Addition has been performed");

最佳答案

我想指出,无论编译错误以及可能的修复如何,扩展 Throwable 都不是一个好主意。

  • 没有必要。您可以/应该扩展ExceptionRuntimeException或其任何子类。

  • 有很多代码假设所有异常都是 ExceptionError 或其子类型,而不是 Throwable 的某些“随机”子类型.

  • Throwable 的随机子类的一般含义尚不清楚;例如请参阅Which subclass of Throwable should be caught and which shouldn't?

另请参阅此问答中的讨论:

<小时/>

异常的构造函数打印或记录错误消息和堆栈跟踪也是一个坏主意。应该由捕获异常的代码来决定如何处理它们。

关于java - 编译错误: unreported exception Add; must be caught or declared to be thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55758167/

相关文章:

python - python 内置的 __exit__ 参数类型是什么?

C++ 为什么这个可以抛出?

c++ - 返回抛出三元运算符?

c++ - 为什么我们需要一个函数 try block ?

java - 作业中索引越界异常

c++ - 三元运算符 : exception throwing and nesting

java - 从不同目录运行 jar 找不到所需的依赖项

java - 使用条件变量阻止生产者消费者 Java 实现

java - 输出为 HTML 而不是纯文本

java - Spring MVC 3 简单表单 Controller