How to throw a checked exception from java thread?

Hey, I am writing a network application in which I read packages of some user-defined binary format. And I start a background thread to wait for incoming data. The problem is that the compiler does not allow me to put code exceptions (marked) in run() . It says:

  run () in (...). Listener cannot implement run () in java.lang.Runnable;  overridden method does not throw java.io.IOException 

I want the exception to kill the thread, and let it be caught somewhere in the parent thread. Is it possible to achieve or execute any exceptions within the thread?

+38
java exception
Sep 02 '09 at 17:54
source share
9 answers

Caution: this may not suit your needs if you need to use an exception mechanism.

If you understand correctly, you really do not need to check the exception (you accepted the answer suggesting the exception), and a simple listener template would be more suitable?

The listener can live in the parent thread, and when you catch the checked exception in the child thread, you can simply notify the listener.

This means that you have a way to show that this will happen (using publicly available methods) and be able to pass more information than the exception allows. But this means that there will be a connection between the parent and child stream (albeit free). In your specific situation, it will depend on whether this takes precedence over throwing a checked exception with an unchecked exception.

Here is a simple example (some code borrowed from another answer):

 public class ThingRunnable implements Runnable { private SomeListenerType listener; // assign listener somewhere public void run() { try { while(iHaveMorePackets()) { doStuffWithPacket(); } } catch(Exception e) { listener.notifyThatDarnedExceptionHappened(...); } } } 

The relationship comes from an object in the parent thread, which must be of type SomeListenerType .

+34
Sep 02 '09 at 20:03
source share

To be able to send an exception to the parent thread, you can put the background thread in Callable (it also allows throwing checked exceptions), which then go to the submit method of some Executor . The submit method returns Future , which can then be used to get an exception (its get will raise an ExecutionException that contains the original exception).

+45
Sep 02 '09 at 20:19
source share

This answer is based on Esko Luontola, but it gives a working example.

Unlike the run () method of the Runnable interface, the call () Callable method allows you to raise some exceptions. Here is an example implementation:

 public class MyTask implements Callable<Integer> { private int numerator; private int denominator; public MyTask(int n, int d) { this.numerator = n; this.denominator = d; } @Override // The call method may throw an exception public Integer call() throws Exception { Thread.sleep(1000); if (denominator == 0) { throw new Exception("cannot devide by zero"); } else { return numerator / denominator; } } } 

The executor provides a mechanism for starting the call inside the thread and for handling any exceptions:

 public class Main { public static void main(String[] args) { // Build a task and an executor MyTask task = new MyTask(2, 0); ExecutorService threadExecutor = Executors.newSingleThreadExecutor(); try { // Start task on another thread Future<Integer> futureResult = threadExecutor.submit(task); // While task is running you can do asynchronous operations System.out.println("Something that doesn't need the tasks result"); // Now wait until the result is available int result = futureResult.get(); System.out.println("The result is " + result); } catch (ExecutionException e) { // Handle the exception thrown by the child thread if (e.getMessage().contains("cannot devide by zero")) System.out.println("error in child thread caused by zero division"); } catch (InterruptedException e) { // This exception is thrown if the child thread is interrupted. e.printStackTrace(); } } } 
+28
Sep 24 '11 at 13:24
source share

I am doing this to catch an exception in a thread and save it as a Runnable member variable. This exception is then opened through the runnable getter. Then I look through all the threads from the parent to see if there are any exceptions and take appropriate action.

+7
Sep 02 '09 at 19:37
source share

If you really can't do anything useful when an exception occurs, you can throw the thrown exception into a RuntimeException.

 try { // stuff } catch (CheckedException yourCheckedException) { throw new RuntimeException("Something to explain what is happening", yourCheckedException); } 
+3
Sep 02 '09 at 18:03
source share

a thread cannot throw an exception for any other thread (nor for the main thread). and you cannot force the legacy run () method to throw any checked exceptions, since you can throw less than the legacy code, not more.

+3
02 Sep '09 at 18:06
source share

If your thread code throws a RuntimeExpection, you do not need to add a throw () throw exception exception.

But use this solution only when necessary, because it can be a bad grade: http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html

Any RuntimeException or unchecked exception can help you. Maybe you need to create your own RuntimeException

+1
Sep 02 '09 at 18:05
source share

Assuming your code is in some kind of loop, you should write:

 public class ThingRunnable implements Runnable { public void run() { try { while(iHaveMorePackets()) { doStuffWithPacket() } } catch(Exception e) { System.out.println("Runnable terminating with exception" + e ); } } } 

An exception will automatically throw you out of your loop, and at the end of the run () method, the thread will stop.

0
Sep 02 '09 at 18:10
source share

Wrapping your exception inside a RuntimeException seems to do the trick.

 someMethod() throws IOException { try { new Thread(() -> { try { throw new IOException("a checked exception thrown from within a running thread"); } catch(IOException ex) { throw new RuntimeException("a wrapper exception", ex); // wrap the checked exception inside an unchecked exception and throw it } }).start(); } catch(RuntimeException ex) // catch the wrapped exception sent from within the thread { if(ex.getCause() instanceof IOException) throw ex.getCause; // unwrap the checked exception using getCause method and use it however you need else throw ex; } } 
-one
Apr 18 '16 at 7:33
source share



All Articles