DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

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.

Rathrola Prem Kumar user avatar by
Rathrola Prem Kumar
·
Mar. 07, 17 · Tutorial
Like (2)
Save
Tweet
Share
5.12K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Blocks Implementation

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • ChatGPT Prompts for Agile Practitioners
  • Top 10 Secure Coding Practices Every Developer Should Know
  • Load Balancing Pattern
  • 5 Factors When Selecting a Database

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: