Try, Catch and Finally Blocks in C# with example

 

Try, Catch and finally are in built objects used in c-sharp to handle the errors in the code.

Try Block:

In try block we write statements that might throw up an error or an exception.

 

 
try {
//code that might  cause an error
}

Catch Block

Catch block catches all error or exception occurred in the try block.It is useful in handling the exception occurred in try block.

 
catch(Type ex){
//code for handling the exception
}

A type can be an Exception class or specific type of exceptions provided by .Net framework.

Exception class is used in a catch block to catch all exception.

If we use specific exception classes like (DivideByZeroException, FileNotFoundException, IndexOutOfRangeException, SqlException, InvalidCastException) then it will throw only that specific type of exception only.

Any kind of exception is thrown like (DivideByZeroException, FileNotFoundException, IndexOutOfRangeException, SqlException, InvalidCastException) they all are inherit from the System.Exception class only.

Finally Block

Finally block is useful in cleaning up any resource that is allocated in the try block.It is always executed even if an exception occurred or not occurred in try block.

 

 
finally {
//code for handling the exception
}

Please Note:

In C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.Try block cannot exist without either catch block or finally block.

Let's see the simple example of Try, Catch and finally block using C# code.

 
        static void Main(string[] args){
       
	  object str = "Onlinebuff";
               try{
				..Some code
	         }catch(Exception ex){
				..Some code
               }finally{
                		..Some code
                }

          }

Above the code we have created three blocks try, catch with Exception class followed by exception object "ex" and finally block.Now let's write some statement in try block where might error occurred.

 

 
static void Main(string[] args){

  object str = "Onlinebuff";
   try{
       int I = (int) str;
    }
}

Above snippet we declared integer variable "i" and we are trying to type cast object "str" which holds string value to integer and assigning same to our integer "I" variable. So it means there is a chance of getting an error in try block lets catch that exception in our catch block.

 
static void Main(string[] args){

       object str = "Questpond";
        try{
              int i = (int)str;
         }catch (Exception ex){
Console.WriteLine("Error Occurred 0} ",ex.Message.ToString());
        }          
}

In above code in our catch block we displayed the exception message so if any error occurred in try block catch block will display that exception message.
Finally lets create a finally block and clean up resources.

 
static void Main(string[] args){

       object str = "Questpond";
        try{
           int i = (int)str;
         }catch (Exception ex){

Console.WriteLine("Error Occurred 0} ",ex.Message.ToString());

        }finally{
        Console.WriteLine("Finally : Cleaning Resources");
        }          
}

Let's display the output with exception message:

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Apr
19
2013

Abstract Class and Abstract Method With An Example Using C#

CLICK TO READ FULL ARTICLE

Views - 48681 |Category - C#

Apr
17
2013

OOPS Principle - Abstraction in C# with an example and explanation

CLICK TO READ FULL ARTICLE

Views - 151370 |Category - C#

Apr
16
2013

What are Delegates in C# - Step By Step Creating and Using the Delegate

CLICK TO READ FULL ARTICLE

Views - 18123 |Category - C#

Nov
19
2012

Difference Between For Loop And For Each Loop in Csharp

CLICK TO READ FULL ARTICLE

Views - 22087 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

jvptc

 

 
Comments

Posted by Mohamemd Akram on 2016-01-28

Thanks for your valuable time for programmer. Thanks for lot.