为什么Runnable的run()无法抛出检查异常? [英] Why cannot run() of Runnable throw checked Exceptions?

查看:159
本文介绍了为什么Runnable的run()无法抛出检查异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 JCIP 的第6.3.2节:

According to section 6.3.2 of JCIP :

Runnable是一个相当有限的抽象.运行无法返回值或引发检查的异常.

Runnable is a fairly limiting abstraction; run can not return a value or throw checked exception .

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()无法抛出检查异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆