Introduction
An exception is an erroneous situation that occurs during program execution. Exceptional situation arise when an operation cannot be completed normally. When an exception occurs in an application, the system throws an error. The error is handled through the process of exception handling.
C# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control.
Exception handling is a way to handle errors at runtime that cause application termination.
.NET supports structured exception handling with the help of try, catch, finally and throw keywords.
C# provides following keywords to handle an exception.
- Try
- Catch
- Finally
The try block
The code, which seems to generate an exception, is placed under the try block. When an exception occurs in the try section, code compilation is transferred to the catch section.
try
{
//Code that may cause an exception
}
A try block should have at least one catch or finally block. We can use both catch and finally block after the try block.
Remember there should be no other code between these blocks.
In the above code if no errors or errors are found, the flow of execution goes to the third block finally. If an exception is thrown execution goes to a catch block.
Exception Nesting
You can create an exception inside of another. This is referred to as nesting an exception.
To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es) clause.
The catch block
In this block you implement methods for dealing with any possible errors of the try block. At the end of this block execution continues to the last code block.
When an exception occurs in the try section, code compilation is transferred to the catch block.
try
{
//Code that may cause an exception
}
catch (...)
{
//Code for handling errors
}
The catch block should be immediately placed after try block.
The following program shows the catch block.
using System;
namespace exception_example1
{
class Program
{
static void Main(string[] args)
{
try
{
int i, k = 0, j;
Console.Write("Enter a number one: ");
i = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number two: ");
j = Convert.ToInt32(Console.ReadLine());
k = i / j;
Console.WriteLine("Output of division : {0}", k);
Console.ReadKey();
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
In the above program if you input the second number as zero (0) it will generate DivideByZeroException.
The catch statement of the catch block takes an object of the exception class as a parameter, which refers to the raised exception. When the exception is caught, the statements within the catch blocks are executed.
One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then access this Exception.Message property to display an error message if you want.
You can have multiple catch blocks after the try block. See the code below.
using System;
namespace exceptionHandling_example3
{
class Program
{
static void Main(string[] args)
{
double Operand1, Operand2;
double Result = 0.00;
char Operator;
Console.WriteLine("This program allows you to perform an operation on two numbers");
try
{
Console.Write("Enter a number: ");
Operand1 = double.Parse(Console.ReadLine());
Console.Write("Enter an operator: ");
Operator = char.Parse(Console.ReadLine());
Console.Write("Enter a number: ");
Operand2 = double.Parse(Console.ReadLine());
if (Operator != '+' &&
Operator != '-' &&
Operator != '*' &&
Operator != '/')
throw new Exception(Operator.ToString());
if (Operator == '/') if (Operand2 == 0)
throw new DivideByZeroException("Division by zero is not allowed");
switch (Operator)
{
case '+':
Result = Operand1 + Operand2;
break;
case '-':
Result = Operand1 - Operand2;
break;
case '*':
Result = Operand1 * Operand2;
break;
case '/':
Result = Operand1 / Operand2;
break;
default:
Console.WriteLine("Bad Operation");
break;
}
Console.WriteLine("\n{0} {1} {2} = {3}", Operand1, Operator, Operand2, Result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);
}
Console.ReadKey();
}
}
}
The finally block
The finally block is executed whether or not an exception was thrown.
try
{
//Code that may cause an exception
}
catch (...)
{
//Code for handling exception
}
finally
{
//clean up code
}
The catch block is used to handle exceptions that occur in a try block. The finally block is used to guarantee the execution of statements, regardless of whether an exception has occurred or not.
See the code to understand finally block
using System;
namespace exception_example1
{
class Program
{
static void Main(string[] args)
{
int i, k = 0, j;
try
{
Console.Write("Enter a number one: ");
i = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number two: ");
j = Convert.ToInt32(Console.ReadLine());
k = i / j;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
Console.WriteLine("Output of division : {0}", k);
Console.ReadKey();
}
}
}
}
Points about finally block
- You can have only one finally block for each try block.
- It is not mandatory to have a finally block after a try block.
- The finally block is used to do all the clean up code.
- It does not support the error message, but all the code contained in the finally block is executed after the exception is raised.
To cover unmanaged resource we use finally block. For example when we are not able to find file/database exception we close the file.
It is used for cleaning up resources that your program might have used and generic code that should always be executed.

Wayne HollierPosted Jun 19, 2019, 5:17 AM
How do I display the error message from another worker class which has a catch block statement. As an example, my home page executes an update statement, this function however resides in a class called DBAction.cs. The function sits inside a catch block and generates an error, how do I throw that error to the home page for display?