Learn how to deal with Exceptions in C#

Trapping and handling of runtime errors is one of the most crucial tasks ahead of any programmer. But before discussing about runtime errors, lets take a look at what the compile time error is.

Compile time errors are errors, which occur during compilation time. It may be due to bad coding, misspelling of syntaxes and so on. It can be corrected by studying the error messages and warnings produced by the compiler.

On the other hand, runtime errors occur at the time of program execution and it can’t be corrected. But a programmer can take preventive measures while coding the program.

For doing so, a programmer should first identify two aspects.

  • (1) Find out part or parts of a program that are most likely to emit runtime errors.
  • (2) Handle those errors according to language conventions.

C# provides an elegant way to handle runtime errors with the help of try, catch and finally keywords. Before moving ahead, let’s consider a situation where the exception is not handled. We will explain the concept with the help of “Division by Zero” example. Listing 1 illustrates how to write a simple program without handling exception:

Listing 1

class Without 
{ 
public static void Main() 
{ 
int x = 5; 
int y = 0; 
int z = x/y; 
Console.WriteLine(z); 
} 
}


When you execute the above program, C# interpreter produces a series of error messages (See figure 1) to notify that runtime error has occurred.

In order to avoid these error messages and provide the user with a user-friendly error message, you should enclose the error prone areas in the above program with the try-catch clause as shown in listing 2:

Listing 2

class With 
{ 
public static void Main() 
{ 
try 
{ 
int x = 5; 
int y = 0; 
int z = x/y; 
Console.WriteLine(z); 
}catch(DivideByZeroException e) { 
Console.WriteLine(“Error occurred, unable to compute”); 
} 
} 
}


When you execute the above program, instead of error messages as in figure 1, the statement inside the catch block (See figure 2) would be printed as our output.

DivideByZeroException is one of the built-in exceptions in C#, defined in System namespace. There are lots of other exceptions, which we will discuss shortly. The base class of all Exception classes in .NET Framework is System.Exception. Even though System namespace defines lot of exceptions, some of them are specified in specialized namespaces like System.Data, System.IO etc. The list given below describes some of the built-in exceptions defined in System namespace.

ArithmeticException

Data Type not matched, invalid casting etc.

DivideByZeroException

An attempt to divide a value by Zero.

FormatException

Incorrect arguments for the methods

MissingMethodException

An attempt to call an invalid method.

OutOfMemoryException

Not enough memory to complete an operation.

OverflowException

An attempt to give large values to a variable of some type.

In listing 2, we have analyzed DivideByZeroException and the way to handle the same. There are many more examples, which you may try on your own.

Using finally clause

In the above listings, the statements inside the catch block would be executed only if an error occurs. If you substitute the value of y to 1 and execute, there will not be any exception. However, there may be some cases where you want something to be printed, no matter the exception had occurred or not. You can do so by making use of finally clause. Listing 3 illustrates this concept by revisiting Listing 2:

Listing 3

class Withfinally 
{ 
public static void Main() 
{ 
try 
{ 
int x = 5; 
int y = 0; 
int z = x/y; 
Console.WriteLine(z); 
}catch(DivideByZeroException e) { 
Console.WriteLine(“Error occurred, unable to compute”); 
} 
finally 
{ 
Console.WriteLine(“Thank you for using the program”); 
} 
} 
}  

Using the Message Property

In certain cases you may have to print the built-in C# error messages when a runtime error occurs. System.Exception namespace defines predefined error messages for every exception. In order to make use of them, you have to use the Message property found in System.Exception namespace. Listing 4 illustrates the working of this property.

Listing 4

class WithMessage 
{ 
public static void Main() 
{ 
try 
{ 
int x = 5; 
int y = 0; 
int z = x/y; 
Console.WriteLine(z); 
}catch(DivideByZeroException e) { 
Console.WriteLine(“Error occurred ” +e.Message); 
} 
} 
} 


Leave a Comment