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

后端 未结 11 1246
醉梦人生
醉梦人生 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条回答
  • You do not need a catch clause to catch exceptions in the Visual Studio debugger. Choose Debug > Exceptions, and select which exceptions you want to catch, all of them if necessary.

    0 讨论(0)
  • 2021-02-07 06:59

    Microsoft recommends not to catch an exception when the only thing you do is to rethrow it immediately (i dont remember the source for now). Your code should only catch exceptions that you want to handle for clean up things or similar actions.

    So generally its not a good practice to catch and rethrow an exception.

    Reasons for catching and replacing it with another exception might be

    • Logging
    • Hiding sensitive information from the caller (Stacktrace, exception details)

    And for debugging you might want to change your "Break when an exception is:"-Handler (Press Ctrl+Alt+e) the value "thrown" on selected CLR Exceptions.

    You might want to take a look at the entlib exception handler block (EHB), with which you can establish a pattern on how to deal with exceptions in your code.

    Regarding your question on performance i think its not a propblem to have many try/catch blocks in your code but you will get performance hits when your code raises and catches many exceptions.

    0 讨论(0)
  • 2021-02-07 07:00

    Since there is zero error handling, this catch is useless. If there was logging or some cleanup done sure, but in this situation I'd get rid of the try/catch.

    0 讨论(0)
  • 2021-02-07 07:05

    Doing it always by default looks like bad design. But there might be reasons for catching and throwing, for example it you want to throw a different exception.

    0 讨论(0)
  • 2021-02-07 07:06

    This can also be useful if you need to inspect something about the exception, and do something for one circumstance or throw it for other circumstances. For instance, if you need to inspect the error number in a SQLException. You can perform a certain action if the error number is one you're prepared to handle. For others you can simply "throw" it so the stack trace is preserved, as mentioned above.

    0 讨论(0)
  • 2021-02-07 07:09

    Yes, it's handy for putting a breakpoint in the catch.

    An alternate and cleaner way is to breakpoint in the constructor of the object you're throwing. You're seeing the program state at a point closer to the source of the error.

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