Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an exception from thread to main thread?

I want to pass an exception from current thread (that thread isn't main thread)to main thread. Why? Because I check my hard lock in another thread (that thread use timer for checking), and when HardLock is not accessible or invalid, I create an exception which is defined by myself and then throw that exception.
So that exception doesn't work well. ;(

like image 290
Rev Avatar asked Aug 04 '10 07:08

Rev


People also ask

Can we throw exception from thread?

the thread can't throw the exception to any other thread (nor to the main thread). and you cannot make the inherited run() method throw any checked exceptions since you can only throw less than the inherited code, not more.

What happens when an exception is thrown by a thread?

An uncaught exception will cause the thread to exit. When it bubbles to the top of Thread. run() it will be handled by the Thread's UncaughtExceptionHandler. By default, this will merely print the stack trace to the console.

Can you catch an exception thrown by another thread in Java?

There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.


2 Answers

Your best bet is to replace the Thread with a Task (new in .NET 4.0). The Task class handles proper marshaling of the exception to whatever thread checks the result of the task.

If using .NET 4.0 is not possible, then CoreEx.dll from the Rx extensions includes an Exception.PrepareForRethrow extension method that preserves the call stack for exceptions. You can use this in conjunction with MaLio's suggestion of SynchronizationContext to marshal an exception to another thread.

like image 179
Stephen Cleary Avatar answered Oct 05 '22 13:10

Stephen Cleary


You can use the exception as an parameter in event.
And handle it after sending the exception to other thread.
Code example.

public delegate void SendToMainDel(string threadName,Exception ex);
public event SendToMainDel SendToMainEv;

public void MySecondThread()
{
    try
    {
    ....
    }catch(Exception ex)
    {
         if(SendToMainEv!=null)
            SendToMainEv("MySecondThread",ex);
    }
}

...
    SendToMainEv += ReceiveOtherThreadExceptions;
...

public void ReceiveOtherThreadExceptions(string threadName,Exception ex)
{ 
   if(InvokeRequired)
   {
      BeginInvoke(new SendToMainDel(ReceiveOtherThreadExceptions), threadName, ex);
      return;
   }

   //there you can handle the exception
   //throw ex;
}
like image 28
Avram Avatar answered Oct 05 '22 13:10

Avram