Articles Zone
I.T DotNet
Home
IT --> DotNet --> Exception Handling
 
Exception Handling in C#


The exception handling in C# is identical to that of Java .The basic syntax of exception handling uses the famous try catch block.If you want to catch an exception in your code you need to enclose that part of code around try catch block.

try
{
throw new Exception ();
}
catch(Exception ex)
{
textBox1.Text = "Exception" + ex;
}


In the above code we are an exception is thrown from within try block.And there is a catch block which handles any exception.Additionally just like SEH (Structured Exception Handling) there can be a finally block after try or try catch block.The code in finally gets executed irrespective of exception being raised by the code within try block.This means even if there is no exception being thrown,finally will be executed and hence finally block can be used to write clean Up code.So in the code below label1 will always display "Finally called " even if there was no exception thrown.

try
{
throw new System.Exception ();
}
catch(System.Exception ex)
{
textBox1.Text = "Exception" + ex;
}
finally
{
label1.Text = "Finally called";
}

You can use catch with no brackets to catch all exceptions

try
{
throw new Exception ();
}
catch
{

}
finally
{
label1.Text = "Finally called";
}

The Exception class is present in the System namespace.The Exception is the base class for all kind of exception.There are serveral specialized classes like ArgumentNullException,ADOException,ArgumentOutOfRangeException,ArithmeticException,COMException

Sign Guestbook View Guestbook