Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C#
Article

Exception Handling in C# with the "Do Not Catch Exceptions That You Cannot Handle" rule in mind

Rate me:
Please Sign up or sign in to vote.
4.38/5 (44 votes)
5 Jan 20064 min read 298.5K   74   33
Exception handling in C# with the "Do Not Catch Exceptions That You Cannot Handle" rule in mind.

Introduction

Microsoft advices in several documents never to do try { ... } catch (Exception ex) { ... } if you don't rethrow the same exception. This document explains how you can attempt to comply to this .NET Framework design guidelines rule: Do Not Catch Exceptions That You Cannot Handle.

Background

After working with Visual Basic 6 error-handling for several years, .NET exception handling comes as a relief. Although it is a major improvement compared to on error goto statements, it does have some problems. Since there are already plenty of resources out there that explain exception handling, I won't do that in this document. Instead, I'll explain how I attempt to comply to one of the .NET Framework design guidelines rules: Do Not Catch Exceptions That You Cannot Handle.

Or in other words: You should never catch System.Exception or System.SystemException in a catch block because you could inadvertently hide run-time problems like Out Of Memory. Refer to the Improving .NET Application Performance and Scalability document on Patterns & Practices website for more information on this rule. An example of something you should not do:

C#
try {
  intNumber = int.Parse(strNumber);
} catch (Exception ex) {
  Console.WriteLine("Can't convert the string to " + 
                             "a number: " + ex.Message);
}

I agree that most of the times you should let the exception propagate up the call stack. However, this doesn't always work for me. For example, suppose I have an unattended application that copies files from one directory to another (it's a stupid example, I know, I just want to prove my point). I want this application to continue working regardless of what goes wrong during the file-copy operation because I'm going to send an e-mail in the end informing the administrator of all the failures. However, I don't want the application to continue if it throws an OutOfMemoryException or a BadImageFormatException for example. This is the C# code of my little application:

C#
static void Main(string[] args)
{
  string[] strFiles = 
      System.IO.Directory.GetFiles(@"C:\Temp");
  System.Collections.ArrayList objSuccesses = 
               new System.Collections.ArrayList();
  System.Collections.ArrayList objFailures = 
               new System.Collections.ArrayList();
  foreach (string strFile in strFiles) 
  {
    try 
    {
      // We're simply copying a file here. 
      // In a real application, 
      //something more complicated would happen...
      System.IO.File.Copy(strFile, strFile + ".new");
      objSuccesses.Add(strFile);
    } 
    catch (Exception ex) 
    {
      Console.WriteLine("Failed to copy the file: " + 
                                             ex.Message);
      objFailures.Add(strFile);
    }
  }
  // We could send an e-mail here informing an 
  // administrator of all failures...
}

If we follow Microsoft's guidelines then we have to catch only those exceptions that could be triggered by the File.Copy method. If you look in the .NET Framework's Class Library, you'll see that this is UnauthorizedAccessException, ArgumentException, ArgumentNullException, PathTooLongException, DirectoryNotFoundException, FileNotFoundException, IOException and NotSupportedException. If you ask me, catching all these exceptions individually is not doable. All I wanted to know is whether or not a file copy failed or not. It would be sufficient to only capture IOException, ArgumentException and NotSupportedException (because all the other exceptions derive from these three exceptions) but to know this I have to read the documentation again. I really don't want to go through that much trouble to simply copy a file.

The guideline assumes that we know all the exceptions that can be thrown by the task executed. Copying a file is a very simple operation that is properly documented by Microsoft. But what if we're using some third-party tool? The stability of our unattended tool depends on the quality of the documentation of this tool. If this third-party forgets to mention one of the exceptions that their tool throws in the documentation, then our unattended application could stop prematurely.

Also, suppose that we know all the exceptions that can be thrown by this tool and suppose that we write our code to handle all these exceptions individually. What happens if we start using a new version of this tool one day? This new version could have the exact same API, but could be throwing more detailed or other exceptions. We therefore need to compare all the exceptions thrown by this tool with the ones that we capture in our code. Again, not doable...

Also, suppose I wanted to use for example the Save method of the System.Drawing.Image class. This method doesn't even list any exceptions; so how can I possibly handle an exception thrown by this method according to the guideline? This method is supposed to save an image to disk; there are dozens of things that can go wrong.

The feature that is missing in C# according to me is the ability to catch all the exceptions except the critical ones. To me Critical exceptions are for example, Out Of Memory, or AppDomain Is Unloading. That's why I wrote a small static method that tests if the exception thrown is a critical one. If it is, the exception is rethrown (the application could also simply stop gracefully). If it isn't a critical exception, it is logged, swallowed and the application continues. This is the code of my IsCritical method:

C#
public static bool IsCritical(Exception ex) 
{
  if (ex is OutOfMemoryException) return true;
  if (ex is AppDomainUnloadedException) return true;
  if (ex is BadImageFormatException) return true;
  if (ex is CannotUnloadAppDomainException) return true;
  if (ex is ExecutionEngineException) return true;
  if (ex is InvalidProgramException) return true;
  if (ex is System.Threading.ThreadAbortException) 
      return true;
  return false;
}

This is the code of the application while using the IsCritical method:

C#
static void Main(string[] args)
{
  string[] strFiles = 
      System.IO.Directory.GetFiles(@"C:\Temp");
  System.Collections.ArrayList objSuccesses = 
                      new System.Collections.ArrayList();
  System.Collections.ArrayList objFailures = 
                      new System.Collections.ArrayList();
  foreach (string strFile in strFiles) 
  {
    try 
    {
      // We're simply copying a file here. 
      // In a real application, 
      // something more complicated would happen...
      System.IO.File.Copy(strFile, strFile + ".new");
      objSuccesses.Add(strFile);
    } 
    catch (Exception ex) 
    {
      if (IsCritical(ex)) throw;
      Console.WriteLine("Failed to copy the file: " + 
                                           ex.Message);
      objFailures.Add(strFile);
    }
 }
 // We could send an e-mail here informing 
 // an administrator of all failures...
}

If you think that using this IsCritical method is a good idea, please let me know. If you know a reason why it's a bad idea, please do let me know.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Team Leader
Belgium Belgium
I am a developer spending most of my time in C#, .NET 2.0 and Sql Server 2005. I am working for a Belgium company called Adam Software developing Asset Management Software. More information about my company and our software can be found at http://www.adamsoftware.net

Comments and Discussions

 
GeneralMy vote of 5 Pin
codejet28-Jan-13 4:43
codejet28-Jan-13 4:43 
QuestionHow critical if we catch out of memory exception manually Pin
kate082416-Feb-12 22:30
kate082416-Feb-12 22:30 
AnswerRe: How critical if we catch out of memory exception manually Pin
Michael Vanhoutte22-Feb-12 2:12
Michael Vanhoutte22-Feb-12 2:12 
QuestionHow do I catch Missing Method exceptions Pin
DonRobb_44-Nov-09 4:47
DonRobb_44-Nov-09 4:47 
QuestionHow do I catch a missing method exceptions Pin
DonRobb_44-Nov-09 4:44
DonRobb_44-Nov-09 4:44 
AnswerRe: How do I catch a missing method exceptions Pin
Michael Vanhoutte4-Nov-09 20:53
Michael Vanhoutte4-Nov-09 20:53 
Generaluse a flag and finally to achieve this Pin
florinlazar6-May-08 21:09
florinlazar6-May-08 21:09 
GeneralRe: use a flag and finally to achieve this Pin
Taneth19-Mar-10 7:54
professionalTaneth19-Mar-10 7:54 
GeneralI agree but... Pin
JEstes19-Apr-07 8:45
JEstes19-Apr-07 8:45 
NewsCaution Pin
michael rempel17-Nov-06 11:38
michael rempel17-Nov-06 11:38 
GeneralThis is not just a C# problem! Pin
Tatworth9-Apr-06 19:38
Tatworth9-Apr-06 19:38 
QuestionHalf way there? Pin
tiefling12-Jan-06 0:27
tiefling12-Jan-06 0:27 
QuestionWhich ones are really critical? Pin
ejp1011-Jan-06 23:27
ejp1011-Jan-06 23:27 
GeneralAnother Critical Exception Pin
S3an13-Jun-05 2:18
S3an13-Jun-05 2:18 
GeneralRe: Another Critical Exception Pin
Michael Vanhoutte13-Jun-05 22:22
Michael Vanhoutte13-Jun-05 22:22 
GeneralNot acceptable for unattended apps. Pin
varnk9-Jul-04 3:02
varnk9-Jul-04 3:02 
GeneralRe: Not acceptable for unattended apps. Pin
skjagini21-Oct-04 11:04
skjagini21-Oct-04 11:04 
GeneralRe: Not acceptable for unattended apps. Pin
zildjohn0110-Aug-05 12:04
zildjohn0110-Aug-05 12:04 
GeneralMy experiences with exceptions in MFC Pin
Nathan Holt at EMOM8-Jul-04 5:51
Nathan Holt at EMOM8-Jul-04 5:51 
GeneralRe: My experiences with exceptions in MFC Pin
Michael Vanhoutte8-Jul-04 11:17
Michael Vanhoutte8-Jul-04 11:17 
GeneralRe: My experiences with exceptions in MFC Pin
Nathan Holt at EMOM9-Jul-04 5:07
Nathan Holt at EMOM9-Jul-04 5:07 
GeneralRe: My experiences with exceptions in MFC Pin
btjdev9-Jul-04 12:30
btjdev9-Jul-04 12:30 
GeneralA posible danger in your method, & something ms could do to help Pin
Nathan Holt at EMOM8-Jul-04 5:31
Nathan Holt at EMOM8-Jul-04 5:31 
It seems to me that a new system could create a different kind of critical error, which your function wouldn't have caught.
Perhaps a part of the problem is that the exception hierachy doesn't provide a way to distinguish minor exceptions from critical ones. I seem to recall that the standard C++ library exception system does have a badexception class or something like it that could be checked for. On the other hand, what a library designer thinks is a bad exception may not be what you think is a bad exception. I've had to deal with annoying exceptions thrown if I move to the beginning of an empty recordset.

Nathan Holt
GeneralRe: A posible danger in your method, & something ms could do to help Pin
Michael Vanhoutte8-Jul-04 11:09
Michael Vanhoutte8-Jul-04 11:09 
GeneralMy opinion Pin
popsickle7-Jul-04 12:34
popsickle7-Jul-04 12:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.