SIGN UP MEMBER LOGIN:    
ARTICLE

Exception Handling in C#

Posted by Rekha Articles | Exception Handling C# August 19, 2009
In this article we will see exception handling technique in C#.
Reader Level:

Exception handling is an in built mechanism in .NET framework to detect and handle runtime errors. The .NET framework contains lots of standard exceptions.

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);
            }
        }
    }

}


 

Login to add your contents and source code to this article
share this article :
post comment
 

In this example, two catch statements are used. The most specific exception, which comes first, is caught.

using System;
class MainClass
{
static void ProcessString(string s)
{
if (s == null)
{
throw new ArgumentNullException();
}
}

static void Main()
{
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}
}
}

Posted by venkatesh reddy May 19, 2010

Hi Senthil,
                 I really appreciate your questions. Cant you post one article covering all these senarios so that it will help beginners in dotnet.

Posted by anil b Mar 03, 2010

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


Posted by Senthilkumar Aug 20, 2009
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor