Exception Handling

An exception is an error condition or unexpected behavior encountered while a program is running. Exceptions are thrown at the runtime and need to be handled by the programmer.

The .Net framework provides us with a number of system-defined exceptions. Some standard exceptions defined by the runtime are listed in a Table.

S.No. Exception Type Description
Exception Base class for all Exceptions.
IndexOutOfRangeException Thrown, when an array is indexed improperly.
NullReferenceException Thrown, when a null object is referenced.
ArgumentException Thrown when one or more arguments of method are not valid.
ArrayTypeMismatchException Thrown when an attempt is made to store an element of the wrong type within an array.
OverflowException Thrown when an arithmetic operation results in an overflow.
ArithmeticException Thrown when the value from an input or arithmetic operation is infinite or cannot be represented in the result type.
DivideByZeroException Thrown when an attempt is made to perform a divide-by-zero arithmetic operation.
InvalidOperationException Thrown by methods when in an invalid state.

Figure: Exception Hierarchy.

Output

There are three ways in which an exception can be handled. These are:

  • Using the try-catch statements
  • Using the try-finally statements
  • Handling with try-catch-finally

Using try and catch

A try statement is used to handle exceptions followed by one or more associated catch blocks. Any code block that has to be monitored for exceptions can be wrapped inside the try block and the associated catch block must immediately follow the try block. The syntax is as follows:

try
{
	[statements]
} 
catch( Exception e) 
{
	[Error Message]
}

Any statement that may produce an error can be placed under the try and catch block. If an exception is thrown from the try block, the exception is captured and processed by the appropriate catch block. The catch block must always specify the class of the exception object it handles. The catch block may or may not have any code block.

Using try and finally

The finally block can also be used along with the try statement. But, there can be only one finally block for one try statement. Finally is used to execute the block of code after try block has exited. If catch block is also present then finally should come after catch.

Handling with try-catch-finally

The best approach is to use try-catch-finally block. The benefit of writing code in finally is that the code in finally block always gets executed whether there is an exception or not.

Multiple catch

Multiple catch statement can be apply to handle different errors, but there is only one try and one finally statement.

class Program
{
	static void Main(string[] args)
	{
		int a = 10, b = 2, c;
		string str = "757657657657657";
		int i;
		try
		{
			c = a / b; //error
			Console.WriteLine("Division = " + c);

			i = Convert.ToInt32(str);
			Console.WriteLine("Value = " + i);
		}
		catch (DivideByZeroException ex)
		{
			Console.WriteLine("Cannot divide by 0");
		}
		catch (OverflowException ex)
		{
			Console.WriteLine("Value out of range");
		}
		catch (Exception ex)
		{
			Console.WriteLine("Some Error");
		}
		Console.ReadLine();
	}
}

Throwing Exceptions

There may be situations where you would explicitly like to throw an exception. To throw an exception explicitly one has to use the throw statement. The throw statement is especially helpful in throwing user defined exceptions. For example, to throw an ArithmeticException, you have to write:

throw new ArithmeticException();

User Defined Exceptions

Besides using the default or system exceptions, a programmer can also create his own set of exceptions. The advantage of creating a user defined exception class is it can hold more information about the error condition than a standard class. This becomes especially more important when the error condition is more complicated.

While writing user defined exceptions, the class that defines the exception must inherit from System.Exception class.

public class MyException : Exception
{
    public MyException()
    {
        Console.WriteLine("My Excecption Class");
    }
    public MyException(string message)
    {
        Console.WriteLine("My Excecption Class " + message );
    }
} 
class Program
{
    static void Main(string[] args)
    {
        try
        {
            throw new MyException("Oh God Exception Occurs");
        }
        catch(MyException e)
        {
        }
        Console.Read();
    }
}