有没有办法让Runnable的run()抛出异常? [英] Is there a way to make Runnable's run() throw an exception?

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

问题描述

我在 run()<中调用的方法/ a>在实现 Runnable 的类中被设计为抛出例外。

A method I am calling in run() in a class that implements Runnable) is designed to be throwing an exception.

但是Java编译器不允许我这样做,并建议我用try / catch包围它。

But the Java compiler won't let me do that and suggests that I surround it with try/catch.

问题在于,通过try / catch包围它我将特定 run()无用。我想要抛出异常。

The problem is that by surrounding it with a try/catch I make that particular run() useless. I do want to throw that exception.

如果我指定抛出 run()本身,编译器抱怨异常与Runnable.run()中的throws子句不兼容。

If I specify throws for run() itself, the compiler complains that Exception is not compatible with throws clause in Runnable.run().

通常我完全没有让< a href =http://developer.android.com/reference/java/lang/Runnable.html#run%28%29 =noreferrer> run()抛出异常。但我有一个独特的情况,我必须具备这种功能。

Ordinarily I'm totally fine with not letting run() throw an exception. But I have unique situation in which I must have that functionality.

如何解决这个限制?

推荐答案

如果要将实现 Runnable 的类传递到线程框架,然后你必须遵循该框架的规则,看看欧内斯特弗里德曼 - 希尔的答案,为什么这样做是一个坏主意。

If you want to pass a class that implements Runnable into the Thread framework, then you have to play by that framework's rules, see Ernest Friedman-Hill's answer why doing it otherwise is a bad idea.

我有预感,但是,你想直接在你的代码中调用运行方法,所以你的调用代码可以处理异常。

I have a hunch, though, that you want to call run method directly in your code, so your calling code can process the exception.

答案这个问题很容易。不要使用Thread库中的 Runnable 接口,而是使用修改后的签名创建自己的接口,允许抛出已检查的异常,例如

The answer to this problem is easy. Do not use Runnable interface from Thread library, but instead create your own interface with the modified signature that allows checked exception to be thrown, e.g.

public interface MyRunnable
{
    void myRun ( ) throws MyException;
}

您甚至可以创建一个将此接口转换为真实<$ c $的适配器c> Runnable (通过处理已检查的异常)适合在Thread框架中使用。

You may even create an adapter that converts this interface to real Runnable ( by handling checked exception ) suitable for use in Thread framework.

这篇关于有没有办法让Runnable的run()抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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