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.

Tags: , ,

.NET | Bad Practices | C# | Exception Handling

Comments


March 6. 2009 01:46
Well explained, also it is worth pointing that if you are using code as above then the program is doing allot of work unwinding the stack.  So generally using exceptions to handle some sort of event is a bad idea, exceptions are for critical errors and as you have said code should test conditions rather than rely on catching an exception.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



This site is Hosted by WebHost4Life

Join WebHost4Life.com

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

© Copyright 2010 X Talks Tech