Why catch and rethrow an exception in C#?

前端 未结 17 644
遥遥无期
遥遥无期 2020-11-22 14:56

I\'m looking at the article C# - Data Transfer Object on serializable DTOs.

The article includes this piece of code:

public static string Se         


        
相关标签:
17条回答
  • 2020-11-22 15:23

    This can be useful when your programming functions for a library or dll.

    This rethrow structure can be used to purposefully reset the call stack so that instead of seeing the exception thrown from an individual function inside the function, you get the exception from the function itself.

    I think this is just used so that the thrown exceptions are cleaner and don't go into the "roots" of the library.

    0 讨论(0)
  • 2020-11-22 15:25

    My main reason for having code like:

    try
    {
        //Some code
    }
    catch (Exception e)
    {
        throw;
    }
    

    is so I can have a breakpoint in the catch, that has an instantiated exception object. I do this a lot while developing/debugging. Of course, the compiler gives me a warning on all the unused e's, and ideally they should be removed before a release build.

    They are nice during debugging though.

    0 讨论(0)
  • 2020-11-22 15:25

    In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).

    0 讨论(0)
  • 2020-11-22 15:25

    Most of answers talking about scenario catch-log-rethrow.

    Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and IncludeThisArgument

    0 讨论(0)
  • 2020-11-22 15:28

    One possible reason to catch-throw is to disable any exception filters deeper up the stack from filtering down (random old link). But of course, if that was the intention, there would be a comment there saying so.

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