AddThis Social Bookmark Button

Print

Learning the C# Error Handling Mechanism

by Budi Kurniawan
09/04/2001

Error handling is an important feature of a programming language. A good error handling mechanism will make it easier for the programmers of that language to write robust applications. This article introduces you to error handling in C# and offers examples on how to use it.

Most older programming languages, such as C and Basic, rely on the heavy use of if statements to detect if an error has occurred. As programs become bigger and more complicated, this approach to that kind of error handling creates more and more insomniacs in the computer programmer profession. Creating robust and reliable large applications is also exponentially more difficult as the number of lines of code increases. More modern programming languages, such as C++, Java, C# and VB.NET, base their error-handling strategy on code isolation. Part of the code that could potentially lead to an error is isolated in a block, and should an error occur, this error is caught and handled locally. This approach seems to work satisfactorily. No more if statement to check the returned value of a function, no more branching that can turn your code into a spaghetti mess.

C# follows Java's and C++'s approach to error handling: throwing exceptions on errors. In C#, to trap an error is to catch it. You use a try ... catch ... finally block to handle errors. You isolate code that could lead to an error in the try clause, and when the error does occur, program control is passed to the code in the catch clause. The optional finally clause will be executed regardless if there was an error or not. The syntax of the try ... catch ... finally block is as follows.

try {
  // code that could lead to an error
}
catch (Exception Type [ variable ]) {
  // code that needs to be executed when an error occurs
}
finally {
  // code that needs to run whether or not an 
  // error has occurred.
}

Note that, unlike in Java, the exception object variable in the catch block is optional.

.NET Exception Classes

Related Reading

C# EssentialsC# Essentials
By Ben Albahari, Peter Drayton & Brad Merrill
Table of Contents
Index
Sample Chapter
Full Description
Read Online -- Safari

C# is part of the Microsoft .NET Framework. C# does not have a type library of its own, but shares the .NET Framework class library with other .NET languages. The .NET class library provides a root class for exception handling: the Exception class in the System namespace. This class is the parent class of all exception classes.

The Exception class has a number of useful properties and methods. For example, its Message property gives you the error message text that you can display on the screen so that your user can report that back to you. Another property, Source, gets or sets a string containing the name of the application or the object that causes the error.

The Exception class has three methods of its own. They are:

  • GetBaseException. This method returns the original, innermost exception that causes this exception and other related exceptions, linked via the InnerException property. If the current exception is the only one thrown, then its reference will be returned.

  • GetObjectData. This method sets SerializationInfo with all of the exception object data targeted for serialization. During deserialization, the exception object is reconstituted from the SerializationInfo transmitted over the stream.

  • ToString. This method returns the fully qualified name of this exception, and possibly the error message, the name of the inner exception, and the stack trace.

The code in Listing 1 illustrates C# error handling in a class named Testing. The Main method of the class has a try ... catch block that will catch any exception that occurs. Consider the for loop in the try clause:

for (int i=5; i>=0; i--) {
  int b = 2/i;
}

The last iteration will have i=0, and a division by zero will occur. What happens then?


Listing 1: A simple exception handling block

using System;
class Testing {
  public static void Main() {
    try {
      for (int i=5; i>=0; i--) {
        int b = 2/i;
      }
    }
    catch (Exception e) {
      Console.WriteLine( e.ToString() );
    }
  }
}

Because the code is placed inside of a try ... catch block, the error won't cause the program to crash. The exception will be caught and control will be passed to the code in the catch clause. The user will see the following in the console:

System.DivideByZeroException: Attempted to divide by zero.

Practically, you can catch all exceptions using Exception in the catch clause. However, when catching an exception, often you want to be more specific, in which case you can then use derivatives of Exception, which we will see in the later section of this article.

Pages: 1, 2

Next Pagearrow