有没有办法在不添加throws声明的情况下抛出异常? [英] Is there a way to throw an exception without adding the throws declaration?
问题描述
我有以下情况。
我有一个Java类,它继承自另一个基类并覆盖一个方法。
基本方法不会抛出异常,因此没有 throws ...
声明。
I have a Java Class that inherits from another base class and overrides a method.
The base method does not throw exceptions and thus has no throws ...
declaration.
现在我自己的方法应该能够抛出异常,但我要么选择
Now my own method should be able to throw exception but I either have the choise to
- 吞下异常
- 添加一个抛出声明
两者都不满意,因为第一个会默默地忽略异常(好吧我可以执行一些记录)由于方法标题不同,第二个会产生编译错误。
Both a not satisfying because the first one would silently ignore the exception (ok I could perform some logging) and the second would generate compiler errors because of the different method headers.
public class ChildClass extends BaseClass {
@Override
public void SomeMethod() {
throw new Exception("Something went wrong");
}
}
推荐答案
你如果你真的想要,可以抛出未经检查的异常,而不必声明它们。未经检查的异常扩展 RuntimeException
。扩展错误
的Throwable也未选中,但只应用于非常严重的问题(例如无效的字节码)。
You can throw unchecked exceptions without having to declare them if you really want to. Unchecked exceptions extend RuntimeException
. Throwables that extend Error
are also unchecked, but should only be used for really serious issues (such as invalid bytecode).
作为具体案例,Java 8添加了 <$ c包装和重新抛出的$ c> UncheckedIOException IOException
。
As a specific case, Java 8 added UncheckedIOException
for wrapping and rethrowing IOException
.
这篇关于有没有办法在不添加throws声明的情况下抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!