Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - EXCEPTION HANDLING


Just imagine, you are asked to enter your gmail Id and Password to login to your Gmail account. But, by mistake you have entered a wrong password. And what if, Gmail exits without giving you a second chance to enter the Password? - It is not acceptable.


Same thing applies for any application. We are allowed to make some sort of mistakes. So that we get a second chance to rectify that. Such mistakes in C# are called as Exceptions.


So, the Exceptions should be handled/caught at runtime, and also the entire application should not close due to that Exception.


It is same as your Gmail account doesn't close when someone types a wrong password and at the same time Gmail needs to keep a track on how many times the user is entering a wrong Password.


Say for example, you have written a program to divide two numbers then add them. But by mistake, you tried to divide the number by zero.


Let us see what happens in the below example.


Example :



class MyApplication
{
	public static void Main(string[] args)
	{
        int x = 3;
        int y = 0;
        int z = x / y;
        System.Console.WriteLine("The divided result is "+z);
        int k = x + y;
        System.Console.WriteLine("The added result is "+k);
	}
} 


Output :



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

So, if you see the above example, we have declared two variables x and y and initialised 3 and 0 to them.


int x = 3;
int y = 0;

Then we tried dividing them,


int z = x / y;

And since, we tried to divide 3 by 0. It ended up with an error.


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

That could be ok. But the problem is, the addition operation was not performed for the above error.


int k = x + y;
System.Console.WriteLine("The added result is "+k);

And the program got halted. Which is not acceptable.


And C# provides a solution to the above problem, with something called as a try - catch block.


try - catch block to handle Exception


So, in the try block, you can place the code if you suspect it might throw error.


And in the catch block, you can handle the error. Only if there is an error, the except block executes.


Now, all you need to do is, place the division operation inside the blocks of try. And if you want to display some message for that error, you can place the message in the catch block.


Now, let's modify the above code using try - catch block.


Example :



using System;

class MyApplication
{
	public static void Main(string[] args)
	{
        int x = 3;
        int y = 0;
        try
        {
            int z = x / y;
            System.Console.WriteLine("The divided result is "+z);
        }
        catch(Exception e)
        {
            Console.WriteLine("The division couldn't be performed due to an error.");
        }
        
        int k = x + y;
        Console.WriteLine("The added result is "+k);
	}
} 


Output :



  The division couldn't be performed due to an error.
  The added result is 3

Now, if you see the above output, it proceeded without any error. So, let us see how it worked.


So, in the above code, we have placed the division operation inside the try block.


try
{
	int z = x / y;
	Console.WriteLine("The divided result is "+z)
}

And as usual an error occurred because we wanted to divide the number by 0.


And luckily, the try block, handled the error. And the control comes to the catch block.


catch (Exception e) {
	Console.WriteLine("The division couldn't be performed due to an error.")
}

Note : Just remember, only if there is an error. The 'catch' block executes.

And prints the output.


The division couldn't be performed due to an error.

And most importantly, the addition operation didn't get halted. And the below line executes, adding two numbers.


var k = x + y
System.Console.WriteLine("The added result is "+k)

Now, let us say, irrespective of any error. You want to display a message.


And C# provides a finally block for that.


try - catch with finally block to handle Exception


The finally block gets executed irrespective of any error.


Let us see the below example, where there is no error.


Example :



using System;

class MyApplication
{
	public static void Main(string[] args)
	{
        int x = 3;
        int y = 3;
        try
        {
            int z = x / y;
            System.Console.WriteLine("The divided result is "+z);
        }
        catch(Exception e)
        {
            Console.WriteLine("The division couldn't be performed due to an error.");
        }
        finally 
        {
            System.Console.WriteLine("try block ended");
        }
	}
} 


Output :



  The divided result is 1
  try block ended

So, in the above program, there is no error. And the finally block got executed.


finally
{
	Console.WriteLine("try block ended");
}

Now, let us say the below program has a division error.


Example :



using System;

class MyApplication
{
	public static void Main(string[] args)
	{
        int x = 3;
        int y = 3;
        try
        {
            int z = x / y;
            System.Console.WriteLine("The divided result is "+z);
        }
        catch(Exception e)
        {
            Console.WriteLine("The division couldn't be performed due to an error.");
        }
        finally 
        {
            System.Console.WriteLine("try block ended");
        }
	}
} 


Output :



  The division couldn't be performed due to an error.
  try block ended

So, the finally block gets executed, whether there is an error or not.