开发者

Does it make sense to catch ThreadAbortException and perform no action?

开发者 https://www.devze.com 2023-02-04 13:23 出处:网络
catch (ThreadAbortException) { } catch (Exception ex) { TraceManager.TraceException(ex, (int)ErrorCode.GENERIC_EXCEPTION,
catch (ThreadAbortException)
{ }
catch (Exception ex)
{
    TraceManager.TraceException(ex,
                                (int)ErrorCode.GENERIC_EXCEPTION,
                                ex.StackTrace + "\n" + ex.Message 开发者_Python百科+ "\n" + VendorUrl);
}

does it make sense to even have the

catch (ThreadAbortException)
{ }

or will that cause the ThreadAbortException to be swallowed and lost forever?


ThreadAbortException cannot be caught "completely"; it will automatically be rethrown at the end of the catch block (see the linked MSDN docs page) unless Thread.ResetAbort is called first.

So, the only sensible catch block would be:

catch (ThreadAbortException)
{
    // possibly do something here
    Thread.ResetAbort();
}

But this has a really evil smell. There's probably no reason to do it, so you may want to rethink your approach.

Update: There are many questions on SO that deal with Thread.Abort:

This one has the same answer as I have given here. This one has an answer that expands on "don't ever call Thread.Abort unless Cthulhu is rising" (which I toned down considerably to an "evil smell").

There are also many others.


The ThreadAbortException can't be caught like that. It will get rethrown automatically at the end of the catch block unless you call Thread.ResetAbort();

Having a catch block as you have here for ThreadAbortException allows it to be auto-rethrown without the catch(Exception) block attempting to handle it.


Calling Thread.Abort on a thread effectively sets a flag which will cause a ThreadAbortException to be thrown any time code isn't processing that exception nor associated finally blocks. Catching the exception without calling Thread.ResetAbort() will simply result in the runtime throwing another ThreadAbortException at its next opportunity. Such behavior is not completely meaningless, however, since it will cause all inner finally blocks to run to completion before the exception can be seen by outer exception-filter blocks. Whether or not that is a good thing will depend upon the application.


If you want to do something specific for different kind of exceptions then it makes since to have seperate catch blocks. Otherwise you can just use the one Exception catch


It will be caught and lost. You should really only be catching exceptions that you can do something with or that you log and then rethrow (with throw; not throw new [some exception];).

0

精彩评论

暂无评论...
验证码 换一张
取 消