Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - Is there a way to make Runnable's run() throw an exception?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a Callable instead, submitting it to an ExecutorService and waiting for result with FutureTask.isDone() returned by the ExecutorService.submit().

When isDone() returns true you call FutureTask.get(). Now, if your Callable has thrown an Exception then FutureTask.get() wiill throw an Exception too and the original Exception you will be able to access using Exception.getCause().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...