In this blog I will told you that how to implement exception
handling mechanism in c#. Here I will describe certain keywords which are used
while we implementing concept of exception handling.
Firstly one thing remember that System.Exception is a base
class for all the exceptions which is generated in c#.net.
We use following keywords while implementing concept of exception handling.
1. try
2. throw
3. catch
4. finally
We enclose a block of code that has the potential of
throwing exception within a try block. A catch handler associated with the
exception that is thrown catches the exception. There can be one or more catch
handler for single try and each catch handler can be associated with a specific
exception type that it can handle. finally block contains that piece of code
which will always executed in all cases whether exception is raised or not such
as cleanup code or disconnection connection from server. We use throw keyword
for throwing exception at certain condition which is caught by try block.
Syntax for exception handling
try
{
//Code
that can encounters errors and raise exceptions.
}
catch
{
//Code
that handles errors and exceptions.
}
finally
{
//Code
that perform cleanup and executes both on normal execution
//path
as well as in case of error occurs.
}
Following example will demonstrate use of try-catch-finally block and throw
keyword.
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ExceptionHandling
{
class Program
{
static void Main(string[]
args)
{
try
{
//Write
down statements to generate exception.
Console.WriteLine("Here is demo of exception handling......!");
throw
new Exception("Oops..! Exception is thrown....");
}
catch(Exception ex)
{
//Dispaly
the error message.
Console.WriteLine("Caught Exception
: {0}", ex.Message);
}
finally
{
//This
is a finally block which always executed.
Console.WriteLine("Ops Finally program end.");
}
}
}
}
Output of following code snippet is as follows.
Here is demo of exception handling......!
Caught Exception:
Oops..! Exception is thrown....
Ops finally program end.