Is it legal and safe in C# to catch an exception on one thread, and then re-throw it on another.
E.g. is this legal
Exception localEx = null;
Thread mythread = new Thread() { () =>
{
try
{
DoSomeStuff();
}
catch(Exception ex)
{
localEx = ex;
}
});
myThread.Start();
...
myThread.Join();
if(localEx != null)
throw localEx; // rethrow on the main thread
I think it is legal, but I'm having trouble finding any doco that proves it. The closest I found was a brief mention of transferring exceptions between threads here: http://msdn.microsoft.com/en-us/library/ms229005.aspx
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
An exception caught by one catch can be rethrown so that it can be caught by an outer catch. To rethrow an exception, you simply specify throw, without specifying an expression.
A Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the exception currently being handled by the Catch statement. The Throw statement resets the call stack for the expression exception.
In C# 5.0, a mechanism was added that enables the throwing of a previously thrown exception without losing the stack trace information in the original exception. This lets you rethrow exceptions, for example, even from outside a catch block and, therefore, without using an empty throw.
Yes, it's legal. Exceptions are (generally speaking) descriptive objects with no thread affinity.
You'd be better off wrapping your thread exception in a new exception:
throw new Exception("Something descriptive here", localEx);
That way, the stack trace in localEx will be preserved (as the InnerException
of the new exception).
What you're doing is not a rethrow. It's a new throw of an exception instance you happened to have in a variable. Even if you were using only a single thread, this would be a bad idea, as it makes the exception look like it came from the "throw" site. With multiple threads, I have no idea how anyone would figure out there had been a thread change.
Absolutely. System.AggregateException is added to .NET 4 for specifically that purpose during parallel operations.
I don't see why it wouldn't work, but you need to remember that you aren't actually rethrowing the exception. You are throwing a new exception, that just happens to be the same exception object. So, for example, the stack trace will say it was thrown from "throw localEx;" instead of wherever the original exception came from.
It is legal and it isn't a rethrow, it's a new exception being thrown on another thread (with the same exception object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With