An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exception is thrown by the CLR or program code if there is an error in the program. These exceptions need to be handle to prevent crashing of program. C# provides built-in support to handle the exception using try, catch & finally block.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.
1.
try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
2.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. Exception raised within try block can be handled using the catch block.
A multiple catch block can also be specified with a different exception type is called exception filters. A multiple catch block is useful when you want to handle different exceptions in different ways.
3.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. The finally block must come after a try or catch block. The finally block is generally used for cleaning-up code e.g. for disposing an unmanaged objects etc. For example, if you open a file, it must be closed whether an exception is raised or not.
4.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword. An exception can be raised manually by using the throw keyword. Any type of exceptions which is derived from Exception class can be raised using the throw keyword.
Syntax of using try, catch and finally block is:
try {
// statements causing exception
}
catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
Example of Exception handling in C# is:
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
Example of throw an exception is:
static void Main(string[] args)
{
Student std = null;
try
{
PrintStudentName(std);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
private static void PrintStudentName( Student std)
{
if (std == null)
throw new NullReferenceException("Student object is null.");
Console.WriteLine(std.StudentName);
}