Skip to main content

Exception Handling Mechanism in .NET

In this article, I will explain you about Exception handling mechanism in .NET

Benefits of reading this article, you can learn below points:

  1. What are types of errors occur in .NET?
  2. Methods to handle an exception
  3. Program to handle an exception using Logical Implementation
  4. Program to handle an exception using try..catch Implementation
  5. Top 10 Interview questions on Exception Handling Mechanism
Exception Handling Mechanism in .NET #dotnet #exceptionhandling Click To Tweet

Let’s begin with Introduction on Exception Handling mechanism,

When we write some code and execute in .NET, there is high possibility of error occurrence as mentioned below

  1. Syntactical Error
  2. Compilation Error
  3. Runtime Error

Syntactical Error:

This error will occur by typing the wrong syntax like missing double quotes, terminators etc.

We as a programmer can identify these minor errors and can easily rectify

Compilation Error:

These errors occur when the program is compiled and errors are like assigning wrong data to a variable, creating an object for interface etc.

This error can be identified and rectify before execution of a program.

Run Time Error:

These errors will occur at the time of executing the program, errors are like entering wrong data into a variable trying to open a file for which there are no permissions, trying to connect database with wrong credentials etc.

What is Exception?

A run-time error is known as Exception, it will cause abnormal termination of the program execution. So, to avoid abnormal termination of program execution, we need to handle the exceptions

Methods to Handle Exception:

There are two methods to handle the exception

  1. Logical Implementation
  2. Try & Catch implementation

Logical Implementation

In this method, we handle the exception by using logical statements, In real time environment first and foremost importance should be given for logical implementation only.

If it’s not possible to handle any exception using logical implementation then we use, try catch implementation.

Let’s see a sample program on how to handle exception using Logical Implementation?

Code Example:

using System;
namespace HandleExceptionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.Write("Enter any two numbers:");
            try
            {
                a = Convert.ToInt32(Console.ReadLine());
                b = Convert.ToInt32(Console.ReadLine());
                c = a / b;
                Console.WriteLine("result is :" + c);
            }
            catch
            {
                Console.WriteLine("error Occured");
            }
            finally
            {
                Console.WriteLine("Code executed");
            }
            Console.Read();
        }
    }
}

Output:

When user enters the second number as Zero, Exception will be raised, this is handling using logical implementation

Try… Catch Implementation

A try can be followed by any number of the catch block, writing finally block is optional.

  • Generic Catch – catch without an exception class. 
  • Specific Catch – catch block used with an exception class.

Try:

This block contains all the statements in which there is possibility of exception occurrence

Catch:

It contains all the statements to handle the exception that is raised within the try block

Process of execution

Execution starts from the try block, if there is any exception occurs in any statement of try block then following lines of exception statement are ignored and control jumps to catch block, then catch block is executed and then finally block.

Let’s see sample program to handle an exception using Try-Catch implementation

Code Example:

using System;
namespace HandleExceptionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.Write("Enter any two numbers:");
            a = Convert.ToInt32(Console.ReadLine());
            b = Convert.ToInt32(Console.ReadLine());
            if (b == 0)
            {
                Console.WriteLine("Second Number cannot be Zero");
            }
            else
            {
                c = a / b;
                Console.WriteLine("Result is :" + c);
            }
            Console.Read();
        }
    }
}

Output:

Properties of Exception Class:

  1. Message
  2. Source
  3. Helplink

List of Exception occurs in Real-time Scenario:

  1. Argument Exception
  2. ArgumentNullException
  3. ArithmeticException
  4. IndexOutOfRange
  5. NullReferenceException
  6. InSufficientException
  7. Much more…

Interview Questions on Exception Handling Mechanism:

  1. What are Runtime Errors?
  2. What are different types of error occurs during program development and execution?
  3. Explain about Logical Implementation?
  4. Explain about try catch implementation? & nested Try catch Implementation?
  5. Properties with Exception Classes
  6. What is Exception?
  7. The process of Exception?

That’s all, hope this article helps you to gain knowledge on Exception Handling Mechanism in .NET.

Thanks for reading and let me know your valuable comments if any.

Like this post? Don’t forget to share it!

This is a guest post by Prem Kumar. If you would like to write for DotnetCrunch, check our guest posting guidelines.

Prem Kumar

I am a Technical Specialist with 4+ years of experience in developing Web-based enterprise applications with special interest in server side services, tools/libraries and frameworks.