C# Exception Handling


  • An exception can be considered as an error which is caused due to a run time error in a program.
  • When the compiler encounters with the error such as dividing by zero, it creates an exception object and informs us that an error has occurred.
  • If we want that the program remains continue executing the remaining code, we have to catch the exception object thrown by the error condition and display an appropriate message for taking corrective action. This process is known as the exception handling.
  • If we do not catch and handle the exception object properly the compiler will display an error message and will terminate the program.

In C# Exception can be divided into two parts:


exception handling

We will discuss these Exceptions in details later, now we are going to discuss some important terms regarding exception handling:


  • try block:The code that may be throw exception which we want to handle is put in the try block. It is followed by one and more catch block.
  • catch block:The code to handle the thrown exception is put in the catch block just after the try block.
  • finally block:finally block is always executed whether the exception is thrown or not by the try block.
  • throw statement:Any method can throw the exception using throw statement when any unexpected event is occur.

Standard Exceptions


  • The exceptions which are pre-defined and provide us with the help of some classes called Exception classes by .NET Class Library are known as Standard Exceptions.
  • These Exception classes are defined in the System namespace.
  • Some of the exception classes present in .NET class library are given below in the table:
  • exception handling
Handling Standard Exceptions using try-catch block

  • The piece of code to handle the exception is written in the try-catch block.
  • When a program starts executing, the program control enters the try block. If all the statements present in try block successfully executed, then the program control leaves the try-catch block.
  • If any statement fails to execute, the execution of remaining statements is stopped and the program control goes to the catch block for handling the exception.

Some facts about try-catch block


  • A try block must be followed by a catch block.
  • A try block can have multiple catch blocks.
  • The try block must lie inside a method.

Here is an example of handling exceptions using try-catch block:


Example

using System;
namespace ExceptionHandling
{
class classA
{
public void division(int x, int y)
{
try
{
int z;
z = x / y;
}
catch (DivideByZeroException e)
{

Console.WriteLine("Cannot divide by zero, it is a logical error.\n Caught an exception:{0}",e);
}

}
static void Main()
{
classA a = new classA();
a.division(4, 0);
Console.ReadLine();
}
}
}

The output of the above program is as follows:


Output

Cannot divide by zero, it is a logical error.
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionsHandling.classA.Division(Int32 x, Int32 y) in C:\Documents and setting...........

Handling Standard Exceptions using try-catch-finally block

  • finally block contains a group of statements that always executes before control leaves the try block.
  • It executed always either exception is thrown by the try block or not.
  • Here is an example of handling the standard exceptions using try-catch-finally block:
Example

using System;
namespace ExceptionHandling
{
class classA
{
public void division(int x, int y)
{
try
{
int z;
z = x / y;
}
catch (DivideByZeroException e)
{

Console.WriteLine("Cannot divide by zero, it is a logical error.\nCaught an exception:{0}", e);
} finally
{
Console.WriteLine("The Divisor program is closing");
}

}

static void Main()
{
classA a = new classA();
a.division(4, 0);
Console.ReadLine();
}
}
}

The output of the above program will be as follows:


Output

Cannot divide by zero, it is a logical error.
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionsHandling.classA.Division(Int32 x, Int32 y) in C:\Documents and setting........
The Divisor Program is closing.

User-Defined Exceptions


  • Sometimes a situation is arises that we have to handle an exception for which there is no exception class defined in the .NET class library.
  • In that cases we are called the classes as user-defined classes and the exception handled by these classes are known as user-defined exceptions.
Handling User-Defined Exceptions

Here is an example which shows the handling of user-defined exceptions:


Example

using System;
using System.Collections.Generic;
using System.Text;
namespace ExceptionHandling
{
class exceptions
{
static void Main()
{
float a = 3;
float b = 20000;
float c;
try
{
c=a/b;
if (c < 0.001f)
{
throw new userexception("number is too small");
}
}
catch (userexception u)
{
Console.WriteLine("exception caught");
Console.WriteLine(u.Message);
Console.ReadLine();
}
finally
{
Console.WriteLine("You are in finally block");
}
}
}
public class userexception : Exception
{
public userexception(string message) : base(message)
{
}
}
}

The output of the above program is as follows:


Output

exception caught
number is too small