Exception Handling in C#

What is Exception?

An exception is a runtime error that arises because of some abnormal conditions, such as the division of a number by zero, passing a string to a variable that holds an integer value. Capturing and handling runtime errors is one of the important and crucial tasks for any programmer; but before we discuss runtime errors, let's take a look at compile-time errors. Compile-time errors are those errors that occur during the compilation of a program. It can happen due to bad coding or incorrect syntax. You can correct these compile-time errors after looking at the error message that the compiler generates. On the other hand, runtime errors are those errors that occur during the execution of a program, and thus at that time, they cannot be corrected. So, necessary actions need to be taken beforehand to prevent such types of errors. To do so, you should first identify the following two aspects:

  • Find out those parts of a program that can cause runtime errors.
  • How to handle those errors, when they occur.

Exception Classes

Exception Class Description
SystemException Represents a base class for other exception classes
AccessException Occurs when a type member, such as a variable, cannot be accessed
ArgumentException Defines an invalid argument to a method
ArgumentNullException Occurs if a null argument is passed to a method that does not accept it
ArgumentOutOfRangeException Occurs if an argument value is not within a range
ArithmeticException Occurs if an Arithmetic overflow or Arithmetic underflow has occured
ArrayTypeMismatchException Occurs if you try to store the incorrect type of object in an array
BadImageFormatException Occurs when the image file of a DLL file or an executable program is valid
DividedByZeroException Occurs if you try to divide a number by zero
FormatException Occurs if there is an incorrect format of argument
IndexOutOfRangeException Occurs if the index of an array is out of bound
InvalidCastExpression Occurs if you try to cast an object to an invalid class
InvalidOperationException Occurs if a method call is invalid for the current state of the object
MissingMemberException Occurs if you try to dynamically access a member of a class that does not exist
NotFiniteNumberException Occurs if a number is invalid or infinite
NotSupportedException Occurs when a method that is invoked is not supported
NullReferenceException Occurs if you try to make use of an unassigned reference
OutOfMemoryException Occurs if an execution stops due to lack of memory
StackOverflowException Occurs if a stack overflows

In C# 2010, exceptions can be handled by using the following two statements:

  • The try...catch...finally statement
  • The throw statement

The try...catch...finally Statement

C# provides three keywords for exception handling- try, catch, and finally. The try block encloses those statements that can cause exceptions; whereas, the catch block encloses the statements to handle the exception if it occurs. Multiple catch blocks can exist for a single try block. The statements enclosed in the finally block are always executed, irrespective of the fact whether an exception occurs or not. There can be only one finally block for a try block.

If any exception occurs in the try block, the program control directly transfers to its respective catch block and later on to the finally block. In C#, catch and finally blocks are not compulsory. In a program, a try block can contain one or multiple catch blocks, only a finally block, or both catch and finally blocks. If no exception occurs inside the try block, the program control is transferred directly to the finally block.

The following code snippet shows the use of the try...catch...finally statement:

try
{
div = 100 / number;
}
catch (DivideZeroException de)
{
Console.WriteLine("Exception Occured");
}
finally
{
Console.WriteLine("Result is : " +div);
Console.ReadLine();
}

In the preceding code snippet, when the statement inside the try block executes, the control may transfer to the catch block depending upon the value of the number variable. Suppose, the value of the number variable is 0, then DivideByZeroException is raised and the program control transfers to the catch block and executes the statements inside the catch block and after that, the statements inside the finally block are executed. If the value of the number variable is other than zero, then the program control is not transferred to the catch block, it is then directly transferred to the finally block, and statements inside the finally block are executed.

The throw Statement

The throw statement is used to raise an exception in case an error occurs in a program. In C#, it is also possible to throw an exception programmatically. You can use the throw keyword to throw an exception. The following code snippet shows an example of the throw statement:

try
{
throw new DivideByZeroException();
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception");
}

In the preceding code snippet, you can see that we have thrown a new DivideByZeroException explicitly.



Write a comment


Name Email Message