问题描述
根据 JCIP 的第6.3.2节:
According to section 6.3.2 of JCIP :
run()
无法返回值,因为其返回类型为void,但是为什么它不能引发已检查的异常?
run()
can not return a value since its return type is void but why can not it throw a checked exception ?
推荐答案
它不能引发受检查的异常,因为从第一个版本开始它没有被声明为引发受检查的异常,因此更改它太危险了.
It cannot throw a checked exception because it wasn't declared as throwing a checked exception from the first version and it is too dangerous to change it.
最初Runnable
仅用于包装的Thread
中,并且假定开发人员希望捕获所有已检查的异常并对其进行处理,而不是将其记录到System.err
中.
Originally Runnable
was only used in a wrapped Thread
, and it was assumed the developer would want to catch all checked exceptions and handle them rather than logging them to System.err
.
Callable
.
Callable
现在允许您返回一个值,并可选地声明一个已检查的异常.
Callable
now allows you to return a value and optional declare a checked exception.
顺便说一句:您可以说不希望返回或从可调用对象中抛出检查异常的一种方法是使用
BTW: One way you can say you don't want a return or throw a checked exception from a callable is to use something like
Callable<Void> callable = new Callable<Void>() {
public Void call() {
// do something
return null;
}
};
这篇关于为什么Runnable的run()无法抛出检查异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!