Exceptions - Fundamentals


Exceptions are used to implement error handling. Exceptions are represented by classes. All exception classes derive from the built in class Exception, which is part of the namespace System.

The classes SystemException and ApplicationException derive from the class Exception. While neither of these classes add anything to Exception, they define the tops of two different exception hierarchies. Several built-in exceptions derive from SystemException, for example DivideByZeroException.

Exception handling is implemented through the following four keywords:

  1. try,
  2. catch,
  3. throw and
  4. finally.

Program statements that are to be monitored are contained within a try block. If an exception occurs in the try block it is thrown. To throw an exception the C# keyword throw is used. At the end of each try block are catch clauses. The catch clauses catch exceptions that are thrown within the try block. Once caught, the exception is passed to a handler specified by a catch clause and the exception is then said to be handled. Any code that must be executed upon exit from a try is put in a finally block.

Using try and catch

The general form of a try-catch block is shown below.

try
 {
   //.... block of code
 }
catch(ExceptionType1 exceptionObject1)
{
 // .... handler for ExceptionType1
}
catch(ExceptionType2 exceptionObject2)
{
 // .... handler for ExceptionType2
}
...
...
...

A number of types of exception may be caught. Above is depicted a try-catch statement with at least two catch clauses. When an exception is thrown, the type of the exception is matched to the types on the catch clauses and only one clause whose type matches is excecuted (the rest of the clauses are then bypassed). If no clause matches, the exception is propagated to any outer handlers. Ultimately, if no other code catches the exception, the C# runtime catches the exception, reports the error and terminates the process. When an exception is caught the exception parameter receives its value. Specifying a parameter object for an exception type is optional (i.e. only the type may be specified). The code inside the clause is called the handler. When the handler is finished executing, control is transferred to the first statement after the final catch clause.