By reading the article, you will learn the points given below.
- What are the types of errors occurring in .NET?
- Methods to handle the exception
- 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
Let’s begin with an introduction on exception-handling mechanisms,
When we write some code and execute it in .NET, there is a high possibility of an error occurrence, as mentioned below.
- Syntactical Error
- Compilation Error
- 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 them.
Compilation Error
This error occurs when the program is compiled and the errors are like assigning wrong data to a variable, creating an object for an interface, etc.
This error can be identified and rectified before the execution of the program.
Run Time Error
This error will occur at the time of executing the program, errors are entering the wrong data into a variable trying to open a file for which there are no permissions, which are trying to connect with the database with wrong credentials, etc.
What is Exception?
A run time 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 the exception, which are given below.
- Logical Implementation
- 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 for logical implementation only.
- If it's not possible to handle any exception, using logical implementation, 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();
}
}
}



SubashPosted Feb 16, 2017, 8:09 PM
Very nice explanation thank you
Rathrola Prem KumarPosted Feb 8, 2017, 7:23 AM
thnq all...... . :)
Pravas RanjanPosted Feb 8, 2017, 1:53 AM
Speechless Kumar.........
Anu VPosted Feb 7, 2017, 11:20 PM
Thanks for sharing.. Nice article..
Manav PandyaPosted Jan 22, 2017, 11:32 PM
Thanks for sharing this article sir ...