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

随声附和 提交于 2019-12-05 16:29:42

问题


catch (ThreadAbortException)
{ }
catch (Exception ex)
{
    TraceManager.TraceException(ex,
                                (int)ErrorCode.GENERIC_EXCEPTION,
                                ex.StackTrace + "\n" + ex.Message + "\n" + VendorUrl);
}

does it make sense to even have the

catch (ThreadAbortException)
{ }

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


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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];).



来源:https://stackoverflow.com/questions/4651589/does-it-make-sense-to-catch-threadabortexception-and-perform-no-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!