Exception Handling




Exception Handling

Exception Handling in C# is a mechanism of handling runtime errors. Exception handling ensures that the program should not halt during the execution. Exception handling does the job of maintaining the flow of the program when some errors occurs. Exceptions that can occur could be anything like logical exception, System Exception etc. The Programmer has to provide some mechanism to handle the exceptions that occur during execution of program to avoid termination of the program.

In C# , the Exception Handling is done with the help of three keywords. TRY,CATCH, and FINALLY. Let's have a look at Syntax.


Syntax

try
{
    //code causing exception.
}
catch(Exception ex)
{
    //code to handle exception.
}
finally
{
    //code which executes irrespective of exception occurs or not.
}




The try block contains the code which can cause Exception to occur. The catch block catches the respective Exception and the Exception is given particular treatment according to code inside catch block. And the finally block contains the code that must execute even if the Exception is occurred or not.

Exception Classes

Following are the Exception classes in C#.

  • IOException- This class handles the Exceptions related to input/Output.

  • DivideByZeroException-This class handles the Exceptions when user tries to Divide Divident by Zero.

  • IndexOutOfRangeException- This class handles the Exceptions when program refers Array index that is out of Range.

  • ArrayTypeMismatchException- This class handles the Exceptions generated when Type Mismatch occurs with Array Data Type.

  • StackOverflowException-This class handles the Exceptions generated by stack overflow.

  • OutOfMemoryException- This class handles the Exceptions when there no sufficient free space for program.

  • InvalidCastException-This class handles the Exceptions generated because of Wrong Type casting.

  • NullReferenceException- This class handles the Exceptions generated when trying to refer Null Objects.


  • The following program shows the exception handling in C Sharp.

    using System;


    namespace exception

    {

         class Program

         {

            static void Main(string[] args)

            {

              int a = 0;

              int b = 1;

              int c;

              try

              {

               c = b / a;

              }

              catch (DivideByZeroException ex)

              {

               Console.WriteLine("Exception raised " +ex.Message.ToString());

               Console.ReadKey();

              }

            }

         }

    }




    Output


    Exception raised Attempted to divide by Zero

    Exception Handling Exception Handling Reviewed by LanguageExpert on August 21, 2017 Rating: 5

    No comments