Share Blog

Monday, April 21, 2014

Exception Handling in C#.NET

Exceptions are unforeseen errors that happen within the logic of an application.Handling of error occurring at Run-time is known as Exception handling. Exception handling is a way to prevent application from crashing.                      Exception handling using - try-catch 


1.try - Wrap the code in a try block that could possibly cause an exception. If a statement in the try block causes an exception, the control will be immediately transferred to the catch block. We can have more than one catch block for one try block.
                    try
                {
              // Statements that can cause exception.
                       }



2.catch - catches the exception and tries to correct the error and/or handles the exception.
     catch(ExceptionType e)
         {
         // Statements to handle exception.
             }



3.finally - Used to free resources. Finally block contains all cleanup codes. Finally block is guaranteed to execute irrespective of whether an exception has occurred or not.
            finally
              {
         // Statement to clean up.
                         }



4.throw - This keyword is used to throw an exception explicitly.
           catch (Exception e)
             {
            throw (e);
                   }


Step- New Project ->New Console Application-> Write code
using System;


namespace ConsoleApplication1
{
    class Div
    {
        int c;
        public void Division(int a, int b)
        {
            try
            {
                c = a / b;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exection caught {0}", e);
            }
            finally
            {
                Console.WriteLine("Exection Result {0}", c);
            }
        }
        static void Main(string[] args)
        {
            Div ob = new Div();
            ob.Division(10,0);
            Console.ReadKey();
        }
    }
}
RESULT



No comments:

Post a Comment