Is there a benefit to JUST a “throw” in a catch?

后端 未结 11 1264
醉梦人生
醉梦人生 2021-02-07 06:42

Been having a \"heated debate\" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a \"throw\" in it e.g.



        
11条回答
  •  青春惊慌失措
    2021-02-07 07:14

    One effect of using a catch and immediate rethrow is that any inner "Finally" blocks will run before the "Catch" occurs (which will in turn be before the exception propagates). This is relevant in two scenarios:

    1. If an exception is ultimately unhandled, it's possible that the unhandled-exception trap may quit the application without running any "finally" blocks. Doing a catch and immediate rethrow will ensure that all "finally" blocks within the catch will execute, even if the exception ends up ultimately being unhandled.
    2. It is possible for code in vb.net, and possibly other languages, to act upon an exception before any finally blocks are run. Using a "try" block with a catch-and-immediate-rethrow will cause the "finally" blocks within that catch block to run before any outer "try" blocks get their first look at the exception.

    An additional caveat with catch-and-immediate-rethrow: for some reason, a catch and immediate rethrow will trash the stack trace's line number for the function call that caused the exception. I don't know why the current function's entry in the stack trace can't be left alone in that case, but it isn't. If one isn't using a .pdb file to get line-number information, this isn't an issue, but if one wants to use such information, it can be annoying.

    Generally, the effects mentioned above aren't desirable, but there are occasions when one or both of the first two effects they may be useful, and the third effect tolerable. In those cases, a catch with immediate rethrow may be appropriate, though the reason for it should be documented.

提交回复
热议问题