Swallowing exceptions - it's just sloppy!

by Xavier Pacheco 24. February 2009 02:20

Recently,I was debugging an application and I was having problems with the application simply shutting down unexpectedly. I debugged further and came across the following code:

      
try
{
   System.Diagnostics.Process.Start(Application.StartupPath.ToString() + 
      "\\client_update.exe");
}
catch
{
}
Environment.Exit(0);

This is what we call swallowing exceptions or eating exceptions. Most seasoned developers would agree that this is a bad practice and should not be done. Basically, an exception is raised in the try block and instead of handling it, it is eaten so that the invoking code never knows it happened. To the end user, the application will simply shut down (actually, I added a throw statement in the catch just to see where it would go and it turns out that the exception is still swallowed at the next level - it just got uglier).

If you find yourself having to consider code like this, think more carefully before you do.  There is probably a better way to handle the error. In this case, a test could have been performed to check for the existence of the file and a meaningful error should displayed to the user to allow them to resolve the problem.

DotnetKicks

Tags: , ,

.NET | Bad Practices | C# | Exception Handling

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 X Talks Tech