Open In App

C# | Exception

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions. Sometimes during the execution of the program, the user may face the possibility that the program may crash or show an unexpected event during its runtime execution. This unwanted event is known as Exception and it generally gives the indication regarding something wrong within the code.

Example: To show the occurrence of exception during divide by zero operation as follows:






// C# program to illustrate the exception
using System;
class Geeks {
        
        // Main Method
        static void Main(string[] args)
        {
  
            // taking two integer value
            int A = 12;
            int B = 0;
  
            // divide by zero error
            int c = A / B;
  
            Console.Write("Value of C is " + c);
              
        }
}

Runtime Error:

Unhandled Exception:
System.DivideByZeroException: Attempted to divide by zero.
at Geeks.Main (System.String[] args) in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.
at Geeks.Main (System.String[] args) in :0



Difference between Errors and Exception

Errors:

Exceptions:

Exception Hierarchy

In C#, all the exceptions are derived from the base class Exception which gets further divided into two branches as ApplicationException and another one is SystemException. SystemException is a base class for all CLR or program code generated errors. ApplicationException is a base class for all application related exceptions. All the exception classes are directly or indirectly derived from the Exception class. In case of ApplicationException, the user may create its own exception types and classes. But SystemException contains all the known exception types such as DivideByZeroException or NullReferenceException etc.

Different Exception Classes: There are different kinds of exceptions which can be generated in C# program:

Properties of the Exception Class: The Exception class has many properties which help the user to get information about the exception during the exception.


Article Tags :
C#