java runnable 异常,有没有办法让Runnable的run()抛出异常?

当在实现Runnable接口的run()方法中需要抛出异常时,Java编译器通常要求使用try/catch包裹。然而,这可能使run()方法失去其应有的功能。解决方法是创建一个新的接口,允许抛出受检查的异常,并创建一个适配器将这个新接口转换为适合Thread框架的Runnable。这样可以在保持功能的同时处理异常。
摘要由CSDN通过智能技术生成

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

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

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

If I specify throws for run() itself, the compiler complains that Exception is not compatible with throws clause in Runnable.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.

How to I work around this limitation?

解决方案

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.

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;

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值