Reader Level:
ARTICLE

Exception handling in C#

Posted by Senthilkumar Articles | Learn .NET September 14, 2009
This article explains about the Exception handling in C# with code example.
  • 0
  • 0
  • 8139

Introduction

The Exception handling provides us the way to avoid the termination of process. The compile time error can be fixed by the programmers during the development phase. But the runtime error occurs not in all feasibility. It may be occur based on the data given by the end user in the run time. The programming languages give the way to us to avoid the program termination and it can assist to do the further actions. Let's see about the exception handling using the Try Catch statements in C# in this article.

Try Catch Exception in C#

Handling the exception is an essential part in any programming language. Like other programming languages, C# supports the exception handling techniques.  Both Java and C# have the features like finally block which helps us to clean the resources allocated in the memory.

Syntax of Try Catch block

Try
{
 //Set of code here
}
Catch (Exception1 class)
{
  //Handle the exception
}
Catch (Exception2 class)
{
  //Handle the exception
}
Finally
{
   //Clean the resources
}
 

Try Statement:

The Try block is entry block in the Try Catch statements. It will execute and if there is any error then only it will terminate to the exception handler block. Otherwise it will find the finally block.

Catch Statement:

It is not mandatory. The catch statement is the exception handler in the Try Catch statements. A try block can have multiple catch blocks. But it must be declared the Exception class is a final one. Because it is the super type in the exception class category. It will throw the error if it is the prior statement to the any exception class. Without any exception class, just catch statement can be used.

Finally Statement:

It is not mandatory. It must execute if it is defined in the Try block. The finally statement must be the final block in the try catch blocks.  It can be combined with Try Catch or Try finally statements. Normally it is used to clean the object resources which are used in the Try block. The process starts from the Try block which is an entry point. If there is any error occurred then it will execute the catch and then it comes to the final block. Finally it must be executed in the finally block.

The execution starts in the try block, it will get execute line by line. When any error occurs then it will be handled in the catch block. However the catch block is not mandatory,

Here I would like to list few key points about this try catch statements

Key points to remember about try Catch exception handling

  • Try is mandatory. It is the entry points and starts the execution here. If there is any error then it goes to  the catch block.
  • However the catch block is not mandatory. It may not have the catch block.

  • Any number of catch blocks can be given to the try catch statement. But the Exception must be the last catch block. Because Exception is the super type in the catch classes.

  • The specific exception classes must be given prior the Exception classes in the Try Catch block. In runtime it will match the appropriate exception class in the catch; if it is not matching then it will be handled in the Exception class.

  • If you define the Catch block prior to the specific exception class then it will throw super type. Because System. Exception has the capability of handle all type of exceptions.
  • Finally block must be last block in the Try...Catch exception handling methods. It is not mandatory.

  • A catch block can have without any exception class.

  • Try...Catch block can be defined without finally or Catch. But Try statement must be defined with either Catch or finally block. Without both Try block cannot be executed independently. More over it must be useless.

  • We cannot terminate the process from the try block to the other statement in case of finally block defined. The statements like GOTO cannot be used to context the process. The finally block is must executable block.

  • The Try block is entry point and finally is exit point. If both are defined then it must be executable blocks in the any try...catch blocks.


Example 1: Simple Try Catch Finally block

using System;
class Example1
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("----------------------------------");
            int d = 0;
            int i = 10 / d;
            Console.WriteLine("Value :" + i.ToString());
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error:" + oEx.Message);
        }
        finally
        {
            Console.WriteLine("----------------------------------");
        }
    }
}

Here try block start to get execute. There is an error in the int I = 10/d then it will switch the process to the catch block and then it get executes the finally block.

Example 2: Multiple Catch blocks

using System;
class Example2
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("----------------------------------");
            int d = 0;
            int i = 10 / d;
            Console.WriteLine("Value :" + i.ToString());
        }
        catch (DivideByZeroException oDiEx)
        {
            Console.WriteLine("Divide By Error:" + oDiEx.Message);
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error:" + oEx.Message);
        }
        finally
        {
            Console.WriteLine("----------------------------------");
        }
    }
}

Here multiple catch blocks are used. When error occurs in the Try block, it finds appropriate exception block. Otherwise it will execute the Exception class.

Example 3: Should not be used like this

using System;
class Example2
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("----------------------------------");
            int d = 0;
            int i = 10 / d;
            Console.WriteLine("Value :" + i.ToString());
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error:" + oEx.Message);
        }
        catch (DivideByZeroException oDiEx)
        {
            Console.WriteLine("Divide By Error:" + oDiEx.Message);
        }

        finally
        {
            Console.WriteLine("----------------------------------");
        }
    }
}
 

Here the Super type exception class used prior to the DivideByZeroException. So it will throw the compile time error. The Exception class must be always last one.

Example 4: Catch without any Exception class

using System;
class Exception4
{
    public static void Main(string[] args)
    {
        try
        {
            int d = 0;
            int Res = 25 / d;
            Console.WriteLine("Result:" + Res.ToString());
        }
        catch
        {
            Console.WriteLine("Error Occured");
        }
        finally
        {
            Console.WriteLine("Sample program for Exception");
        }
    }
}

Example 5: Try Finally block.

using System;
class Exception5
{
    public static void Main(string[] args)
  {
    try
    {
     Console.WriteLine("----------------------------------------------------------------");
    }
   Finally
   {
      Console.WriteLine("Example program");
     Console.WriteLine("----------------------------------------------------------------");
 
  }
  }
}

Example 6: Cannot be used like this

using System;
class Exception5
{
    public static void Main(string[] args)
    {
        try
        {
            int d = 0;
            int Res = 25 / d;
            Console.WriteLine("Result:" + Res.ToString());
        }
    }
}

 It will throw the compile time error. The Try block must be combined with either Catch blocks or finally block.

Conclusion:

So far, we have seen about the Try Catch exception handling techniques in this article. Still there are many other ways to handle the exception techniques in C# combined with ASP.Net. Like the following.

  • Page_error event handling in the ASP.Net page

  • Throw exception

  • Application_error in the global.ascx

  • Custom errors tag in the web.config file.

  • Custom errors in the IIS.

I have planned to write one more articles which will be covering all the above methods.

Please post your feedback, suggestions and corrections regarding this article.

COMMENT USING

Trending up