Saturday, March 5, 2011

try catch finally in c sharp


Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
Introduction
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 an exception if one exists. The finally can be used for doing any clean up process. The general form try-catch-finally in C# is shown below


try
{
 // Statement which can cause an exception.
}
catch(Type x)
{
 // Statements for handling the exception
}
finally
{
 //Any cleanup code
}
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
But 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.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
Uncaught Exceptions
The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can’t find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.
using System;
class MyClient
  {
 public static void Main()
 {
  int x = 0;
  int div = 100/x;
  Console.WriteLine(div);
 }
  }
The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.
//C#: Exception Handling
using System;
class MyClient
{
 public static void Main()
 {
  int x = 0;
  int div = 0;
 try
 {
  div = 100/x;
  Console.WriteLine(“This line in not executed”);
 }
 catch(DivideByZeroException de)
 {
  Console.WriteLine("Exception occured");
 }
 Console.WriteLine("Result is {0}",div);
 }
}
In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements. If a finally block is present, the code inside the finally block will get also be executed.
//C#: Exception Handling
using System;
class MyClient
{
 public static void Main()
 {
  int x = 0;
  int div = 0;
 try
 {
  div = 100/x;
  Console.WriteLine(div);
 }
 catch(DivideByZeroException de)
 {
  Console.WriteLine ("Exception occured");
 }
 finally
 {
  Console.WriteLine("Finally Block");
 }
 Console.WriteLine("the Result is {0}";
}
Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
class MyClient
{
 public static void Main()
 {
  int x = 0;
  int div = 0;
 try
 {
  div = 100/x;
  Console.WriteLine(div);
 }
 finally
 {
  Console.WriteLine("Finally Block");
 }
 Console.WriteLine("the Result is {0}";
}
But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block
Multiple Catch Blocks
A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.
//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
 public static void Main()
 {
  int x = 0;
  int div = 0;
 try
 {
  div = 100/x;
  Console.WriteLine("Not executed line");
 }
 catch(DivideByZeroException de)
 {
  Console.WriteLine("DivideByZeroException" );
 }
 catch(Exception ee)
 {
  Console.WriteLine("Exception" );
 }
 finally
 {
  Console.WriteLine("Finally Block");
 }
 Console.WriteLine("Result is {0}",div);
 }
}
Throwing an Exception
In C#, it is possible to throw an exception programmatically. The ‘throw’ keyword is used for this purpose. The general form of throwing an exception is as follows.
 throw exception_obj;
For example the following statement throw an ArgumentException explicitly.
 throw new ArgumentException(“Exception”);
//C#: Exception Handling:
using System;
class MyClient
{
 public static void Main()
 {
 try
 {
  throw new DivideByZeroException("Invalid Division");
 }
 catch(DivideByZeroException e)
 {
  Console.WriteLine("Exception" );
 }
 Console.WriteLine("LAST STATEMENT");
 }
}
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common languageruntime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.
System.OutOfMemoryException
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.ArithmeticException
System.DevideByZeroException
System.OverFlowException
User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.
using System;
class MyException : Exception
{
 public MyException(string str)
 {
  Console.WriteLine ("User Defined Exception");
 }
}
class MyClient
{
 public static void Main()
 {
  try
  {
   throw new MyException ("Rajesh");
  }
  catch(Exception e)
  {
   Console.WriteLine ("Exception caught here" + e.ToString ());
  }
  Console.WriteLine("Last Statement");
 }
}
Design Guidelines
Exceptions should be used to communicate exceptional conditions. Don’t use them to communicate events that are expected, such as reaching the end of a file. If there’s a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn’t going to handle, consider whether it should wrap that exception with additional information before re-throwing it.

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.


SqlConnection myConn = new SqlConnection("Connectionstring");
        try
        {
            myConn.Open();
            //make na DB Request                
        }
        catch (Exception DBException)
        {
            //do somehting with exception
        }
        finally
        {
           myConn.Close();
           myConn.Dispose();
        }
try
{
    // Code here that might throw an exception...

    if (arbitraryCondition)
    {
        return true;
    }

    // Code here that might throw an exception...
}
finally
{
    // Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}

try
{
    doSomething();
}
catch
{
    catchSomething();
}
finally
{
    alwaysDoThis();
}
When you can do this:
try
{
    doSomething();
}
catch
{
    catchSomething();
}

alwaysDoThis();
 Try-Catch-Finally Syntax 
        try
        {
            //Even if a goto statement were here            //control gets transferred to the statement identified in            //goto statement only after executing the finally block.        }

        catch        {
            //Catch the exception        }

        finally        {
            //this block of code will always get executed whether an            // exception occurs or not as long as there are no exceptions            // within this block itself. If an Exception is thrown here            // some outer try block should handle it            //Any Clean up code goes here. Especially to release any            //system resources such as file handles and network            //connections        }


Let's go through an example so that we can better understand the purpose of the finally block. Listing 7.7 illustrates the use of the finally block to clean up file states.

Listing 7.7: Exception7.cs, TestFinally 


namespace
 TestFinally
{
    using System;
    using System.IO;
    /// <summary>    /// Summary description for TestFinally.    /// </summary>
    public class TestFinally    {
        public TestFinally()
        {
                      // TODO: Add Constructor Logic here        }

        public static void Main()
        {
            StreamReader sr1 = null;
            StreamWriter sw1 = null;

            try            {
                System.Console.WriteLine("In try block");

                //Open files                sr1 = new StreamReader(File.Open("Test1.txt",
                System.IO.FileMode.Open));
                sw1 = new StreamWriter(File.Open("Test2.txt",
                System.IO.FileMode.Append,
                FileAccess.Write));

                while (sr1.Peek() != -1)
                {
                    sw1.WriteLine(sr1.ReadLine());
                }

                goto MyLabel;
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Concat(e.Message,
                e.StackTrace));
            }

            finally            {
                //Int32 j ;                //j=0;                //j=j/5;                //If an Exception is thrown here some outer                //try block should handle it. The finally block                // will not be completely executed                Console.WriteLine("In finally block");
                //we need to make sure that Close method of the                //Streamreader sr1 or StreamWriter sw1                //is called irrespective of whether an exception                // occurs or not                //to release any system resources associated with                //the reader or writer
                if (sr1 != null)
                {
                    sr1.Close();
                }

                if (sw1 != null)
                {
                    sw1.Close();
                }
            }

        MyLabel:
            Console.WriteLine("In Mylabel");
            // note: the following statements are not allowed            //inside a finally block:            //return, goto, break and continue

 
            Console.ReadLine();
        }
    }
}

No comments :

Post a Comment