Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Exception Handling Mechanism In .NET

DZone's Guide to

Exception Handling Mechanism In .NET

In this tutorial, you'll learn about the various methods of handling exceptions in your code, and how to various methods of implementation to fix these errors.

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

By reading the article, you will learn the points given below:

  • What are the types of errors occurring in .NET?
  • Methods to handle exceptions.
  • Program to handle an exception, using Logical Implementation.
  • Program to handle an exception, using Try-Catch Implementation.
  • Top 10 Interview questions on Exception Handling Mechanism.
    Image title

Handling Mechanisms

Let’s begin with an introduction to exception handling mechanisms. When we write some code and execute it in .NET, there is a high possibility of one of the following errors occuring: 

  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 easily rectify them.

Compilation Error

This error occurs when the program is compiled, and the errors, like assigning wrong data to a variable, creating an object for the interface, etc., occur. This error can be identified and rectified before the execution of the program.

Runtime Error

This error will occur at the time of executing the program. Some typical errors are: entering the wrong data into a variable; and trying to open a file for which there are no permissions, which are trying to connect with the database with the wrong credentials.

What is an Exception?

A runtime error is known as an exception, as it will cause abnormal termination of the program execution. To avoid abnormal termination of the program execution, we need to handle the exceptions.

Methods to Handle an Exception:

There are two methods to handle exceptions, which are given below:

  1. Logical Implementation
  2. Try-Catch implementation

Logical Implementation

In this method, we handle the exception by using logical statements. In real time environments, the first and foremost importance should be given to logical implementation only. If it's not possible to handle any of the exceptions using logical implementation, then we use try catch implementation.

Let’s see a sample program on how to handle an exception, using Logical Implementation:

Code

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
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();  
        }  
    }  
}   


When the user enters the second number as zero, an exception will be raised. This is handling, using logical implementation.

Try-Catch Implementation

A try block can be followed by any number of catch blocks, where writing final blocks is optional. If a catch block is used without an exception class, it is known as a Generic Catch block. If catch block is used with an exception class, it is known as a Specific Catch block.

Try

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

Catch

This block contains all the statements to handle the exception, which is raised within the try block.

Process of Execution

The execution starts from the try block, if there is any exception which occurs in any statement of the try block, then the lines of exception statement given below are ignored and control jumps to the catch block. Subsequently, the catch block is executed and then the final block. It's simple.

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

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
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();  
             
        }  
    }  
}  

Your output should appear as follows: 

Properties of Exception Class

  1. Message
  2. Source
  3. Helplink

A list of exceptions that occur in real-time scenarios is given below:

  1. Argument Exception
  2. ArgumentNullException
  3. ArithmeticException
  4. IndexOutOfRange
  5. NullReferenceException
  6. InSufficientException
  7. T.C.

Interview Questions on Exception Handling Mechanism

  • What are Runtime Errors?
  • What are the different types of errors which occur during program development and execution?
  • Explain Logical Implementation.
  • Explain Try-Catch Implementation and Nested Try-Catch Implementation.
  • What are the properties of the Exception Classes?
  • What is an Exception?
  • What is the process of an Exception?

I hope this article helps you gain knowledge on an exception handling mechanism in .NET.

Thanks for reading and let me know your valuable comments.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
.net 4 ,web dev ,exception handling

Published at DZone with permission of Rathrola Prem Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}