我正在编辑别人的代码,并且一个方法有“Throws Throwable”。我把它去掉了,所以 Eclipse 会让我只添加它需要抛出的异常类型...但是,我在调用父类(super class)(我当前无法访问)的方法上有一个错误,上面写着“未处理的异常类型 Throwable ”。
根据我所知道的以及我在这个鳕鱼中看到的内容,我的猜测是这是不应该做的事情......但有人可以确认吗?
最佳答案
有时,方法声明方法抛出异常
是合理的。通常,需要更具体的异常(exception)情况。
例如,Callable接口(interface)有一个抛出异常的方法:
public interface Callable<V> {
V call() throws Exception;
}
Throwable
可以是异常或错误。错误表示应用程序不应 try catch 的异常。任何方法都可以抛出它,并且不需要声明它。
摘自 Joshua Bloch 的《Effective Java》,第二版:
"Always declare checked exceptions individually, and document precisely the conditions under which each is thrown using the Javadoc @throws tag. Don't take the shortcut of declaring that a method throws some superclass of multiple exception classes it can throw. As an extreme example, never declare that a method "throws Exception" or, worse yet, "throws Throwable."
这几乎总是最好的指导方针,除了布洛赫绝对禁止“抛出异常”的一些异常(exception)情况。
关于java - "Throwable"应该被抛出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934912/