我想通过添加创建用户定义的异常,但出现编译错误。
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
都不是一个好主意。
没有必要。您可以/应该扩展
Exception
或RuntimeException
或其任何子类。有很多代码假设所有异常都是
Exception
或Error
或其子类型,而不是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/