By 22/07/2015 16 Comments

C# Exception Handling

  • Exceptions are different types of errors which occurs at run-time in an application and it terminates immediately.
  • Exceptions are occurs in an application when any operation/method is failed or the end user enters an invalid information or handle wrongly to an application.
  • C# provides us a well-known structure which helps us to handle these run-time errors easily, that structure is called The exception handling.
  • C# defines the block of code to handles the all type of exceptions, that block of code is called “the exception handlers” which are executed automatically when the errors are occurred.

An exception can be handled through four keywords: try, catch, throw and finally. These keywords are associated with each other.

try:

  • The program statements or code which generates exceptions are must be placed inside try keyword block.

catch:

  • An exception is caught and handle by the keyword catch. A catch block also defines an exception type and its reference variable.

throw:

  • It is used to throw an exception manually.

finally:

  • It is an optional, it is always executed whether an exception is occurred/thrown or not. Mostly it contains any cleanup code which should be executed such as a database connection, any network or file stream needs to be closed which is already opened in try keyword block. Remember if our program does not contain any cleanup code, then there is no need of finally code block.


Example – 1

using System;
namespace csharpBasic
{
    class ProgrammingLanguages
    {
        // 2 string type arrays are declared.
        string[] Languages = new string[4];
        string[] SetNames = { "Asp.net", "Php", "Css", "Html", "Javascript", "Jquery" };
        
        // A void type method is declared.
        public void Display()
        {
            Console.WriteLine("Before exception is occured.");

            // for loop iterates each elements from an array.
            for (int count = 0; count < SetNames.Length; count++)
            {
                Languages[count] = SetNames[count];
                Console.WriteLine(Languages[count]);
            }
            Console.WriteLine("This line does not display.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ProgrammingLanguages programmingLanguages = new ProgrammingLanguages();

            try
            {
                // Display method is being called inside try.
                programmingLanguages.Display();
            }

            // catch keyword declaration with an exception type.      
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("catch{} block is executed because an " + ex.Message + " exception is caught");
            }

            // finally keyword must be executed and display string message.           
            finally
            {
                Console.WriteLine("finally{} block is executed.");
            }
            Console.ReadKey();
        }
    }
    /*  The Output will be:
     
        Before exception is occured.
        Asp.net
        Php
        Css
        Html
        catch{} block is executed because an Index was outside the bounds of the array.
        exception is caught
        finally{} block is executed.
     */
}


Example – 2, multiple catch blocks:

using System;
namespace csharpBasic
{
    class ExceptionExample
    {
        // An int array is initialized.
        int[] Numbers = { 1, 2 };

        // A void type method declration.
        public void Devision(int number, int devidedBy)
        {
            Console.WriteLine("Division " + number + "/" + devidedBy + " = " + (number / devidedBy));
        }

        // Void type method GetArray().
        public void GetArray()
        {
            // for loop loops through each int number and assigns into an array.
            for (int count = 0; count < 4; count++)
            {
                Numbers[count] = count;
                Console.WriteLine(Numbers[count]);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ExceptionExample exceptionExample = new ExceptionExample();

            try
            {
                // 2 methods are being called inside try.
                exceptionExample.GetArray();
                exceptionExample.Devision(10, 0);
            }

            // DivideByZeroException is handled by catch.
            catch (DivideByZeroException)
            {
                Console.WriteLine("1st catch{} block is being executed because a DivideByZeroException caught");
            }

            // IndexOutOfRangeException is handled by catch.
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("2nd catch{} block is being executed because a IndexOutOfRangeException caught");
            }

            finally
            {
                Console.WriteLine("finally{} block is executed.");
            }
            Console.ReadKey();
        }
    }
    /*  The Output will be:
     
        0
        1
        2nd catch{} block is being executed because a IndexOutOfRangeException caught
        finally{} block is executed.
     */
}


REMEMBER:

  • C# provides several types of exceptions which can be occurred such as IndexOutOfRangeException etc.
  • One or multiple catch blocks can be declared and it can be associated with a single try block.
  • A particular catch block will be executed if a matching exception of that type is occurred, in this case all other catches will be bypassed.
  • When an exception is occurred it is automatically caught by a particular catch and its value is received by an exception reference variable ex such as IndexOutOfRangeException ex, here ex is an optional reference variable, it is only needed when we want to access that exception object’s members and any extra information related with that exception such as ex.Message etc. Therefore it is not necessary to declare a reference variable of an exception type.
  • If no exception is occurred inside a try, it ends normally, it’s all catches are bypassed and execution is passed to the next code/statement after the last catch.
  • A catch is executed only if an exception is generated.
  • When an exception is occurred inside a try then it is terminated immediately and passes the control to a catch.
  • Remember the type of an exception is must be matched with the specified type in a catch otherwise an exception will not be caught.





Next Tutorial →


← Previous Tutorial


Posted in: C# Advance, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .