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

后端 未结 5 2243
旧时难觅i
旧时难觅i 2021-02-20 01:31
catch (ThreadAbortException)
{ }
catch (Exception ex)
{
    TraceManager.TraceException(ex,
                                (int)ErrorCode.GENERIC_EXCEPTION,
                    


        
相关标签:
5条回答
  • 2021-02-20 01:43

    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.

    0 讨论(0)
  • 2021-02-20 01:44

    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.

    0 讨论(0)
  • 2021-02-20 01:45

    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

    0 讨论(0)
  • 2021-02-20 02:01

    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 讨论(0)
  • 2021-02-20 02:03

    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.

    0 讨论(0)
提交回复
热议问题