The exceptions are anomalies that occur during the execution of a program.
"Exception is a runtime error which arises because of abnormal conditions in a condition in a sequence."
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles exception if one exists. The finally can be used for doing any clean up process.
The general form of try-catch-finally in c# is shown below:
try
{
// Statements which can cause an exception
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
// Any Cleanup Code
}
Example of Exception Handling:
using System;
namespace ConsoleApplication1
{
class main
{
public static void Main()
{
int[] a = new int[5];
int i;
try
{
for (i = 0; i < 7; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
}
catch (Exception ex)
{
Console.WriteLine("Please Check The Error Limits...");
}
for (i = 0; i < 5; i++)
{
Console.WriteLine("Array Element Is " + a[i]);
}
}
}
}
Program to divide two numbers using Exception Handling:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int x, y, z = 0;
try
{
Console.WriteLine("Enter The Value of X");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter The Value of Y");
y = Convert.ToInt32(Console.ReadLine());
z = x / y;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.WriteLine("The Division is : " + z);
}
}
}
}

Gowtham RajamanickamPosted Apr 18, 2015, 3:54 AM
good one
SenthilkumarPosted Aug 20, 2009, 6:10 AM
Hey author, I think this is not full fledged one. Can you test the following things? Can you give the multiple catch block in the single try...catch??? try { //Some code here } catch(Exception oEx) { } catch(SqlException oEx) { } finally { } then what will happend? Can you give like this??? try { } catch { } then what will happen? Catch block is mandatory??? try { } finally { } then what will happen? In asp.net application i have given like this I have written page_error event then in page_load i have handled the try...catch exception. And also i have written application_error event. If there is an error in the page_load event code. Then which one will handle the error??? With regards, Erode Senthilkumar