Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...
 


Thursday, March 16

Bad ExceptionHandling

Stumbled upon this today :



Quite useless! Should be :



Why?
  • Exception should be logged. Why else catch exception and do nothing but (re-)throwing exception?!
  • Exception must be re-thrown with the throw; statement. Using throw ex; will erase your original stacktrace because a new stacktrace is started at that point. Use throw; to maintain your stacktrace and re-throw the exception! Confusing?! You can check this behavior in IL DASM : difference between throwing and rethrowing statement.

1 Comments:

  • At 11:04 AM, Anonymous Gabriel Lozano-MorĂ¡n said…

    Hello Pieter

    I want to add that in some situations it is okay to throw a new exception instead of rethrowing the exception but there are only 2 reasons why you want to do this:
    1) when you want to add more richer information to the exception
    2) when you want to throw a more meaningful exception to the caller.

     

Post a Comment

Links to this post:

Create a Link

<< Home