SIGN UP MEMBER LOGIN:    
ARTICLE

Exception/Error Handling in C#: Part 1

Posted by Abhimanyu Kumar Vatsa Articles | Exception Handling C# June 13, 2011
In this quick article you will learn Error Handling mechanisms available in C#.
Reader Level:

Introduction

In programming, exceptions/errors can happen (appear) at any time and use of traditional techniques to manually add error-detecting code around every statement is cumbersome and time consuming. C# makes it easy to separate the error-handling code from the code that implements the main flow of the program by using exceptions and exception handlers. To write exception-aware programs, we need to do two things:

(i) By placing statements inside a try block

All statements placed inside try blocks are executed and if none of the exceptions appear, run all code one by one until the end. If any error condition occurs, execution jumps out from the try block to the catch block.

(ii) By using one or more catch handlers

If any one statement in a try block generates an exception, then the runtime examines the appropriate catch handler and jumps to that.

Example

try
{
    //statements
}
catch (OverflowException oEx)
{
    Label1.Text = oEx.Message;
}
catch (FormatException fEx)
{
    Label1.Text = fEx.Message;
}
catch (Exception ex)
{
    Label1.Text = ex.Message;
}

In above example, I am using multiple catch handlers. The first one, OverflowException appears when we try to handle a value which is outside the range of Data Type. The second one, FormatException appears when we try to calculate (mathematical task) a string value without parsing it to corresponding numeric Data Type. You must understand that multiplication is only possible for numeric Data Types, or even if we need to multiply two strings then we must parse them first otherwise we will receive a FormatException. In the third one the exception occurs when none of above (OverflowException and FormatException) exceptions are satisfied.

catch (Exception ex)  //general catch handler
{
    Label1.Text = ex.Message;
}

The above exception isthe universal exception; the exception-catching mechanism provided by C# and the Microsoft .NET Framework is quite comprehensive. The .NET Framework defines many types of exceptions, and any programs we write can throw most of them. It is highly unlikely that we'll want to write catch handlers for every possible exception that our code can throw. The answer to this question lies in the way the different exceptions are related to one another. Exceptions are organized into families called inheritance hierarchies. FormatException and OverfowException both belong to a family called SystemException, as do a number of other exceptions. SystemException is itself a member of a wider family simply called Exception, which is the great-granddaddy of all exceptions. If we catch Exception, the handler traps every possible exception that can occur.

If we want to catch Exception, we can actually omit its name from the catch handler because it is the default exception:

catch
{
    //statements
}

However, this is not always recommended. The exception object passed in to the catch handler can contain useful information concerning the exception, which is not accessible when using the above catch handler.

Matching Multiple Exceptions

One question here; what happens when the same exception matches multiple catch handlers at the end of a try block? If we catch FormatException/OverflowException and Exception in two different handlers, which one will run (or will both execute)? The answer is, when an exception occurs, the first handler found by the runtime that matches the exception is used, and the others are ignored. One more question here, what happens when we place a handler for Exception before a handler for FormatException/OverflowException, the FormatException/OverflowException handler will never run. It will show an error. Therefore, we should place more specific catch handlers above a general catch handler after a try block. If none of the specific catch handlers matches the exception, the general catch handler will.

Further Reading

http://msdn.microsoft.com/en-us/library/system.exception(v=VS.100).aspx

HAVE A GREAT CODING!!

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor