1. OnlineBuff

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:

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 and lots more. Follow me @ and twitter.... read more

Comments

64x64
By Mohamemd Akram on 2016-01-28
Thanks for your valuable time for programmer. Thanks for lot.

Add a Comment