Vyoms OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Bookmark and Share Rss Feeds

Exception Handling in .NET Framework | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Sponsored Ads
Hot Jobs
Fresher Jobs
Experienced Jobs
Government Jobs
Walkin Jobs
Placement Section
Company Profiles
Interview Questions
Placement Papers
Resources @ VYOMS
Companies In India
Consultants In India
Colleges In India
Exams In India
Latest Results
Notifications In India
Call Centers In India
Training Institutes In India
Job Communities In India
Courses In India
Jobs by Keyskills
Jobs by Functional Areas
Learn @ VYOMS
GATE Preparation
GRE Preparation
GMAT Preparation
IAS Preparation
SAP Preparation
Testing Preparation
MBA Preparation
News @ VYOMS
Freshers News
Job Articles
Latest News
India News Network
Interview Ebook
Get 30,000+ Interview Questions & Answers in an eBook.
Interview Success Kit - Get Success in Job Interviews
  • 30,000+ Interview Questions
  • Most Questions Answered
  • 5 FREE Bonuses
  • Free Upgrades

VYOMS TOP EMPLOYERS

Wipro Technologies
Tata Consultancy Services
Accenture
IBM
Satyam
Genpact
Cognizant Technologies

Home » Articles » Exception Handling in .NET Framework

Exception Handling in .NET Framework








Article Posted On Date : Thursday, March 22, 2012


Exception Handling in .NET Framework
Advertisements

Overview

The .NET Framework has enhanced the ways in which you deal with errors. C#'s mechanism for handling error conditions allows you to provide custom handling for each type of error condition as well as to separate code that identifies errors from the code that handles them.

What is an Exception?

Exceptions are unusual error conditions that occur during execution of a program or an application. Whenever an exception is occurred the .NET runtime throws an object of type "XXXException" All the Exceptions thrown by .NET runtime have their base class as Exception. There are varieties of system exceptions that are thrown. Please find some of the Exceptions thrown by the .NET runtime.

    OutOfMemoryException

    NullReferenceException

    InvalidCastException

    ArrayTypeMismatchException

    IndexOutOfRangeException

    ArithmeticException

    DivideByZeroException

    OverFlowExceptio

Be Proactive rather than reactive: It is always a better practice to write code in a manner to avoid exceptions rather than catching and handling the same. This approach may not be possible for all kinds of Exception since it is tough to anticipate OutOfMemoryException and avoid the same.

How to Handle Exceptions in .NET 2.0?

In .NET we have the try and catch block that enables us to handle the exceptions

Example 1:.

try
{
// Code where we are anticipating Exceptions
}
catch (Exception)
{
// Code to Handle the Exception
}
finally
{
// Code that needs to be executed in any case
// typically cleaning up code
}

The try and catch block are mandatory for handling exceptions. Finally, the block is optional. It is always a better practice to handle exceptions that are anticipated. If we are dealing with a database we need to handle the SQL Exception. The code on try should be the code that anticipates any kind of exception. It is a common practice that is observed that all the code in a function is moved to a try. Such programming should not be encouraged.

Example 2:

try
{
    int i = 0;
    String str = String.Empty;
    Hashtable ObjHashTable = new Hashtable();
    // Here the actual code
}
catch (Exception)
{
    // Code Handle the Exception
}

Exceptions are caught in the Catch Block. Once an Exception is caught, there are number of ways for handling the same.

Catching an Exception (eating away the exception)

This kind of handling mechanism is the least encouraged one. The problem with the approach given below is that if an exception is caught, it is not logged. This can have serious problems to the application while diagnosing in case of any problem.

Example 3:

try
{
    // Code where we are anticipating the Exception
}
catch (Exception)
{
    //Do Nothing
    // Just Eat Away the Exception
}

Re-Throwing an Exception

The handling mechanism involved here will catch an exception and will re-throw another exception. As we can see from Example 4, UnauthorizedAccessException is caught and another exception ApplicationAccessFailedException is thrown. ApplicationAccessFailedException is a custom exception. We will deal about the custom exceptions in later sections.

Example 4:

try

{

// Code where we are anticipating the Exception

}

catch (UnauthorizedAccessException ObjUnAuthorizedException)

{

ApplicationAccessFailedException ObjApplicationAccessFailedException = new ApplicationAccessFailedException();

ObjApplicationAccessFailedException.InnerException = ObjUnAuthorizedEnxception;

throw ObjUnAuthorizedException;

}

Showing an Error Message to User

This kind of Exception Handling mechanism is the most commonly used mechanism. As we can see from Example 5, in the catch block a message is shown to the user..

Example 5

try
{
    // Code where we are anticipating the Exception
}
catch (Exception)
{
    System.Windows.Forms.MessageBox.Show("Error Message: This is the Message shown to the User");
}

The message shown to the user can be an error message, warning message or an Information message.

What are Custom Exceptions? Why do we need them?

Custom Exceptions are exceptions that are created for applying the Business rules of the Application. These exceptions are used to implement the business rules violations of the application.

Definition of Business Rules:

Business rules or business rule sets describe the operations, definitions and constraints that apply to an organization in achieving its goals. These rules are then used to help the organization to better achieve goals, communicate among principals and agents, communicate between the organization and interested third parties, demonstrate fulfillment of legal obligations, operate more efficiently, automate operations, perform analysis on current practices, etc.

For example: The minimum balance set for Savings A/C in a bank would be different from a Current A/C. Hence, while developing the application for the same the Business rule would be kept as the same.

Violation of Business Rule: Whenever a Violation of Business rule is done, it should be notified and the proper message should be shown to the user. This will be handled by a Custom Exception. Let us illustrate the same with an example.

Example 6

private void ValidateBeforeDebit(float Amount)
{
    {
        if((Balance �" Amount ) < MimimumBalanceNeedToHave)
        {
            throw new MimimumBalanceViolationForSavingsAccount("Current TransactionFailed: Mimimum Balance not available");
        }
         Else
        {
            Debit(Amount);
        }
    }
}

We have a method ValidateBeforeDebit (). This method ensures the minimum balance. If there is no minimum balance then a Custom Exception of the type MimimumBalanceViolationForSavingsAccount is thrown. We need to handle the method whenever we call the method.






Sponsored Ads



Interview Questions
HR Interview Questions
Testing Interview Questions
SAP Interview Questions
Business Intelligence Interview Questions
Call Center Interview Questions

Databases

Clipper Interview Questions
DBA Interview Questions
Firebird Interview Questions
Hierarchical Interview Questions
Informix Interview Questions
Microsoft Access Interview Questions
MS SqlServer Interview Questions
MYSQL Interview Questions
Network Interview Questions
Object Relational Interview Questions
PL/SQL Interview Questions
PostgreSQL Interview Questions
Progress Interview Questions
Relational Interview Questions
SQL Interview Questions
SQL Server Interview Questions
Stored Procedures Interview Questions
Sybase Interview Questions
Teradata Interview Questions

Microsof Technologies

.Net Database Interview Questions
.Net Deployement Interview Questions
ADO.NET Interview Questions
ADO.NET 2.0 Interview Questions
Architecture Interview Questions
ASP Interview Questions
ASP.NET Interview Questions
ASP.NET 2.0 Interview Questions
C# Interview Questions
Csharp Interview Questions
DataGrid Interview Questions
DotNet Interview Questions
Microsoft Basics Interview Questions
Microsoft.NET Interview Questions
Microsoft.NET 2.0 Interview Questions
Share Point Interview Questions
Silverlight Interview Questions
VB.NET Interview Questions
VC++ Interview Questions
Visual Basic Interview Questions

Java / J2EE

Applet Interview Questions
Core Java Interview Questions
Eclipse Interview Questions
EJB Interview Questions
Hibernate Interview Questions
J2ME Interview Questions
J2SE Interview Questions
Java Interview Questions
Java Beans Interview Questions
Java Patterns Interview Questions
Java Security Interview Questions
Java Swing Interview Questions
JBOSS Interview Questions
JDBC Interview Questions
JMS Interview Questions
JSF Interview Questions
JSP Interview Questions
RMI Interview Questions
Servlet Interview Questions
Socket Programming Interview Questions
Springs Interview Questions
Struts Interview Questions
Web Sphere Interview Questions

Programming Languages

C Interview Questions
C++ Interview Questions
CGI Interview Questions
Delphi Interview Questions
Fortran Interview Questions
ILU Interview Questions
LISP Interview Questions
Pascal Interview Questions
Perl Interview Questions
PHP Interview Questions
Ruby Interview Questions
Signature Interview Questions
UML Interview Questions
VBA Interview Questions
Windows Interview Questions
Mainframe Interview Questions


Copyright © 2001-2024 Vyoms.com. All Rights Reserved. Home | About Us | Advertise With Vyoms.com | Jobs | Contact Us | Feedback | Link to Us | Privacy Policy | Terms & Conditions
Placement Papers | Get Your Free Website | IAS Preparation | C++ Interview Questions | C Interview Questions | Report a Bug | Romantic Shayari | CAT 2024

Fresher Jobs | Experienced Jobs | Government Jobs | Walkin Jobs | Company Profiles | Interview Questions | Placement Papers | Companies In India | Consultants In India | Colleges In India | Exams In India | Latest Results | Notifications In India | Call Centers In India | Training Institutes In India | Job Communities In India | Courses In India | Jobs by Keyskills | Jobs by Functional Areas

Testing Articles | Testing Books | Testing Certifications | Testing FAQs | Testing Downloads | Testing Interview Questions | Testing Jobs | Testing Training Institutes

Gate Articles | Gate Books | Gate Colleges | Gate Downloads | Gate Faqs | Gate Jobs | Gate News | Gate Sample Papers | Gate Training Institutes

MBA Articles | MBA Books | MBA Case Studies | MBA Business Schools | MBA Current Affairs | MBA Downloads | MBA Events | MBA Notifications | MBA FAQs | MBA Jobs
MBA Job Consultants | MBA News | MBA Results | MBA Courses | MBA Sample Papers | MBA Interview Questions | MBA Training Institutes

GRE Articles | GRE Books | GRE Colleges | GRE Downloads | GRE Events | GRE FAQs | GRE News | GRE Training Institutes | GRE Sample Papers

IAS Articles | IAS Books | IAS Current Affairs | IAS Downloads | IAS Events | IAS FAQs | IAS News | IAS Notifications | IAS UPSC Jobs | IAS Previous Question Papers
IAS Results | IAS Sample Papers | IAS Interview Questions | IAS Training Institutes | IAS Toppers Interview

SAP Articles | SAP Books | SAP Certifications | SAP Companies | SAP Study Materials | SAP Events | SAP FAQs | SAP Jobs | SAP Job Consultants
SAP Links | SAP News | SAP Sample Papers | SAP Interview Questions | SAP Training Institutes |


Copyright ©2001-2024 Vyoms.com, All Rights Reserved.
Disclaimer: VYOMS.com has taken all reasonable steps to ensure that information on this site is authentic. Applicants are advised to research bonafides of advertisers independently. VYOMS.com shall not have any responsibility in this regard.