There are no exceptions in C arid in C++ one can get away from using them with error handling functions such as exit() and terminate(). In C# these functions are absent and we introduce exceptions which take their place. The exception handling in C#, and Java is quite similar.
When a program has a bug we can intercept it in the flow of execution by inserting an error handling statement. To catch a particular type of exception in· a piece of code, you have to first wrap it in a ‘try’ block and then specify a ‘catch’ block matching that type of exception. When an exception occurs in code within the ‘try’ block, the code execution moves to the end of the try box and looks for an. appropriate exception handler. For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:
try
{
int zero = 0;
res = (num/ zero);
}
catch (system.dvideByzeroException e)
.{
Console.writeLine(“Error: an attempt to divide by zero”);
}
You can specify multiple catch blocks (following .each other), to catch different types of exception. A complication results, .however, from the fact that exceptions form an object hierarchy, so a particular exception might match more than one catch box. What you have to do here is put catch boxes for the more specific exceptions before those for the more general exceptions. At most one catch box will be triggered by an exception, and this will be the first (and thus more specific) catch box reached.
For example, program, which does not, accesses the first element of an array. Then, during some array handling operations, if an access to array[O] is attempted, the’ OutOfRange exception is thrown. class OutOfRange is an exception class. ‘Allexception classes inherit from Exception class. Compiler, will give an error if the inheritance from, the Exception class is not made .
In the code that follows we throw an exception OutOfRange if i == 0 is true. The try statement is enclosing the part of the code where the exception is expected. If the exception occurs it is handled by the code inside the catch statement. The catch statement takes as an argument an instance of class System.Exception.
Exception Handling Program
using system;
class OutOfRange:Exception
{
}
class Demo
{
int n;
public int []array;
public Demo ( int n)
{
this.array = new int[n];
this.n = n;
}
public void show_element (int i)
{
try
{
if (i == 0) throw ( new OutOfRange());
catch (Exception e)
{
console.writeLine(“Exception :{0}”,e);
}
console.WriteLine (array [i]);
}
}
class Test
{
public static void Main()
{
Demo test = new Demo (3);.
test.array [1] = 2;
test.array [2] = 3;
test.show_element (0);
}
}
OUTPUT:
Exception: OutOfRange: An exception of type outOfRange was thrown. at Demo.show_element(Int32 i) in
Go:\cSharpEd\excep.cs:line 19
The above program can be simplified if you use a built in Exception class provided by the C# runtime. The full list of built in Exception classes hasn’t been published yet by Microsoft at the time of this writing.
In the following program we use built in ArgumentException instead of OutOfRange exception.
A better way to handle an Argument exception
using system;
class Demo
{
int n;
public int []array;
public Demo (int n)
{
this.array = new int En];
this.n= n;
},
pub1ic void· show_element (int i)
{
try
{
i f (I == 0)
throw new ArgumentException (“Out of rannge”);
}
catch (ArgumentException e)
{
console.writeLine(“Exception :{0}”,e);
return ;
}
Console.WriteLine (array[i]);
.}
}
class Test
{
public static void Main()
{
Demo test = new Demo(3);
test.array[l] = 2;
test.array[2] =3;
test.show_element (0);
}
}
Following the last ‘catch’ box you can also include a ‘finally’ box. This code is guaranteed to run whether or not an exception is generated. It is especially useful for cleanup code where this would be skipped in the ‘try’ box following an exception being thrown.
Where an exception is not caught by any of the subsequent ‘catch’ boxes, the exception is thrown upwards to the code which called the method in which the exception occurred (note that in C# the methods do not declare what exceptions they are throwing). This exception will keep on bubbling upwards until it is either caught by some exception handling in the code or until it can go no further and causes the program to halt.
Note that the exceptions a program throws need not be limited to those automatically generated. A program can throw exceptions-including customized exceptions-whenever it wishes, using· the ‘throw’ command. The code below gives examples of all the statements discussed above, with the ‘getException’ method showing how. to throw an exception.
using System;
public class ExceptionDemo
{
public static void Main ()
{
try
{
getException();
}
catch (Exception e)
{
Console.writeLine(“we got an exception”);
}
finally
{
Console.writeLine(“The end of the program”);
}
}
public static void getException()
{
throw new Exception();
}
}