C# - Exception Handling

Introduction

In this article, we will discuss exception handling and its keywords. Let me talk our day to day normal general life terminology, suppose you are viewing this exception handling article, so by mistake net connectivity disconnected or there is some problem with your system suddenly something goes wrong. For example- power problem or your system is not working, so immediately your system not in condition to continue. Similarly in C#  the exception occurs when something unexpected or unwanted event happened that disturb the normal flow of program. To over come this exception is raised or runtime error raised inside application, so we need to handle that exception to handle the exception we have exception handle mechanism.

Exception handling

Exception is an unnecessary or abnormal event, which takes place during the execution of program at run time that obstructs the flow of code. Exception handling is one of the influential concepts to handle the run time error (when we are trying to create object to an abstract class). 

Lets discuss with an example :

 static void Main(string[] args)
        {
            int a, b, c;
            Console.WriteLine("Enter Two Number:");
            a= Convert.ToInt32(Console.ReadLine());
            b= Convert.ToInt32(Console.ReadLine());
            c = a / b;
            Console.WriteLine("Quotient is :", +c);
            Console.Read();
        }

In this program we make it runtime error here that is exception we make it how we get we can see solution explorer then goes in properties.

Expand the startup object click on our class name  and then run the application.

First enter two digit number for example if we enter first number 25 and second is  0.

So any number divided by zero is infinity in this case we make it exception that is attempted to divide by zero so this is abnormal termination of program.

Exception handling Keyword in C#

In C#, there are three build-in keywords to handle the exception.

  1. try
  2. catch
  3. finally

Try

The try is used to define a block where we put the exception code. In this try block in this statement any exception or run time error is there, immediately is ignore so control is jump in to catch block.  We can’t use try block only, it must goes with either catch or finally.

try{statement....... }

Catch

The catch keyword is used to handle the exception. We can’t use catch block only. It must contain a try block before this.  We can use multiple catch blocks and after catch the finally block can be used.

catch{statement.....}

catch block are two type first one is generic catch block means without exception class is called generic catch block and second one is specific catch block means with exception class is called specific catch block.  

Finally

The finally keyword is used to perform the essential code of the program. It must perform whether an exception is handled or not. finally block is compulsory executing i.e, exception is raised in try block or not because including finally block is optional

finally{statement....}

try
{
//we put the exception code
}
catch
{
//to handle the exception
}
finally 
{
//this block must performed
}

Let’s discuss examples of C# exception handling in which we implement try catch block to handle the exception.

Example 1

I have implemented total logic part in try block ,control firstly jumps in to try block, in try block any run time exception immediately it ignore and jump in to catch block and finally also execute. In try block code  there no exception simply try block execute catch block ignore and finally block execute.

 static void Main(string[] args)
        {
            try 
            {
                int a, b, c;
                Console.WriteLine("Enter Two Number:");
                a = Convert.ToInt32(Console.ReadLine());
                b = Convert.ToInt32(Console.ReadLine());
                c = a / b;
                Console.WriteLine("Quotient is :", +c);
            }
            catch
            {
                Console.WriteLine("exception occur");

            }
            finally
            {
                Console.WriteLine("code is excuted");
            }
            Console.Read();
        }

Output

Pre-define exception classes
 

S.no Exception class  Description
1 TimeoutException The time span which is given for a particular task has been expired
2 StackOverflowException Raises when exceeding from given memory space
3 OutOfMemoryException When a program doesn't get the enough memory to execute the code.
4 OverflowException Arithmetic operations and conversions which results in exceed the size of datatype
5 NullRefrenceException Throws when a program tries to fetch member a type whose value is NULL.
6 NotSupportedException Throws when a method or operation is not supported.
7 KeyNotFoundException Occurs when a key specified for accessing an element in a collection does not match with the given key collection.
8 IndexOutOfRangeException Occurs when an array index is outside from lower and upper bounds of an given array.
9 FormatException Occurs when a value is not in an appropriate format to be converted from a string by typecasting method.
10 FileNotFoundException Occurs when a physical file does not exist in particular location.
11 DivideByZeroException Occurs when an integer value is divided by zero.
12 ArgumentOutOfRangeException Occurs when a value of argument is out of range from the valid value.
13 ArgumentNullException Occurs when NULL argument passed in method.


Conclusion

This article was about exception handling with some examples to clear the concept of exception handling. Exception handling prevents the unnecessary termination of the program. It maintains the normal flow of code.