Loading, please wait...

A to Z Full Forms and Acronyms

What is C# Exception Handling ?

May 11, 2020 C#, .Net, Exception Handling, 3694 Views
In this article, you’ll learn about the exceptions in detail and how to handle them in your code for a smooth runtime.

The way our lives are surrounded by problems likewise the codes that we write is swamped with bugs, errors, and exceptions. As in life, we move further handling and overcoming our problems which makes us a better individual, similarly being able to solve the errors of our code makes us a better programmer. So, let us take a glance at various errors in C#.

In C#, Errors are of the following two types:

  1. RUNTIME ERROR: This occurs due to the wrong implementation of logic or if wrong input is supplied.
  2. COMPILE TIME ERROR: It’s basically syntactical errors.

The compiler checks only syntactical errors and not logical errors because logic may be different for different individuals. On the other hand, runtime errors are dangerous because it leads to abnormal termination of the program without running the remaining lines of code.

And this abnormal termination of the program occurs because of exceptions. Also, we can say exceptions are classes that abnormally terminate the program when runtime errors occur.

Various exception classes are as follows: -

  1. IndexOutOfBoundException
  2. DivideByZeroException
  3. Overflow Exception
  4. Format Exception

Let us go through the below code to understand the exceptions more clearly,

using System;
class Ex
 {
    static void Main()
    {   Console.Writeline(“enter 1st no.”);
         int x = int.Parse(Console.Readline());
         Console.Writeline(“enter 2nd no.”);
         int y = int.Parse(Console.Readline());
         int z = x/y;
         Console.Writeline(“result” +z);
    }
}

Code Explanation:

If we provide x=100, y=0 as input for the above code and as soon as  CLR i.e. Common Language Runtime (CLR is the execution engine for running the programs in C# and all the programs run under the supervision of CLR) comes to this line of above code int z = x/y; the CLR knows that this operation cannot be permitted because 100/0 is against the universal rule so CLR picks the class associated with this error i.e. DivideByZeroException class is picked by the CLR and CLR creates the object of this class and throws this object which leads to the abnormal termination of the program and hence an error message is displayed that the remaining lines of code cannot be executed.

We cannot leave exceptions so to handle exceptions we use exception handling which is a mechanism of stopping the abnormal termination of the program whenever a runtime error occurs. To handle the exceptions we use the try-catch blocks

Image Source: google search

What is Try and Catch Blocks are:

The try statement use like a block to write the code statement where the errors may come at while execution/runtime.

The catch statement allows you to define a block of code to be executed if an error occurs in the try block. You can add multiple catches to handle different types of runtime errors / Exceptions.  If you will use more than one catch block you need to define the respective type of exception and this allows you to write the logic to handle them differently.

SYNTAX OF TRY CATCH BLOCKS:

try
{
   //statements which does not require execution when the runtime error occurred
}
catch( <exception class name> <variable>)
{
   //statements which should execute only when there is a runtime error i.e. corrective action 
}     

Now we write the previous code using the try-catch blocks

using System;
class Ex
 {
    static void Main()
    {
        try
        {   Console.Writeline(“enter 1st no.”);
            int x = int.Parse(Console.Readline());
           Console.Writeline(“enter 2nd no.”);
           int y = int.Parse(Console.Readline());
            int z = x/y;
            Console.Writeline(“result” +z);
         }
       catch(DivideByZeroException e1)
        {
         Console.Writeline(ex1.Message);
         }
    Console.Writeline(“end of program”);
    }
}
  • In this case again if we provide x=100, y=0 as input then the previous process will again be repeated i.e. CLR will create an instance of DivideByZeroException class and throws it.
  • Now the instance is coming to abnormally terminate the program but before the termination, the catch block catches the instance and as the instance is caught by the catch block, the abnormal termination stops, and that instance is stored under the variable of catch block and in the above program as e1.
  • This mechanism of exception handling can be thought of as the situation that a ball is coming to hit the window but if somebody catches the ball the window glass won’t break. As in the code, the instance is caught by the catch block so the abnormal termination doesn’t occur.

Conclusion:

In this article, we have learned, what is Exception and which type of exception can be in C# also we have seen the way to handle them using Try and catch blocks.

A to Z Full Forms and Acronyms