C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Exception Handling in C#


Posted Date: 02 Oct 2009    Resource Type: Articles    Category: .NET Framework
Author: Muhammad JavedMember Level: Gold    
Rating: 1 out of 5Points: 10



Waht is Exception


Exception is a situation that occurs when our program encounters an error that it is not
expecting during runtime. Examples of exceptions include trying to divide a number by zero,
trying to write to a file that is read - only, trying to delete a nonexistent file, and trying to access
more members of an array than it actually holds. Exceptions are part and parcel of an application,
and as a programmer we need to look out for them by handling the various exceptions that may
occur. That means our program must be capable of responding to the exceptions by offering some
ways to remedy the problem instead of exiting midway through our program (that is, crashing).

Exception Handling
At very first it is neccessary to understand the importance of handling exceptions, consider the following case, a classic
example of dividing two numbers:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int num1, num2, result;
Console.Write(“Please enter the first number:”);
num1 = int.Parse(Console.ReadLine());
Console.Write(“Please enter the second number:”);
num2 = int.Parse(Console.ReadLine());
result = num1 / num2;
Console.WriteLine(“The result of {0}/{1} is {2}”, num1, num2, result);
Console.ReadLine();
}
}
}

There are several opportunities for exceptions to occur in this example:
1.. If the user enters a noninteger value for num1 or num2 .
2.. If the user enters a non - numeric value for num1 and num2 .
3.. If num2 is zero, resulting in a division by zero error.
Handling Exceptions Using the try - catch Statement
In C Sharp, we can use the try - catch statement to enclose a block of code statements that may potentially
cause exceptions to be raised. We enclose these statements within the catch block and that block to catch
the different types of exceptions that may occur.
Using the previous example, we can enclose the statements that ask the user to input num1 and num2
and then performs the division within a catch block. We then use the catch block to catch possible
exceptions, like this:

static void Main(string[] args)
{
int num1, num2, result;
try
{
Console.Write(“Please enter the first number:”);
num1 = int.Parse(Console.ReadLine());
Console.Write(“Please enter the second number:”);
num2 = int.Parse(Console.ReadLine());
result = num1 / num2;
Console.WriteLine(“The result of {0}/{1} is {2}”,
num1, num2, result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}

The Exception class is the base class for all exceptions; that is, it catches all the various types of
exceptions. The class contains the details of the exception that occurred, and includes a number
of properties that help identify the code location, the type, the help file, and the reason for the exception.
The following chart describes these properties.
Property Description
Data Gets a collection of key/value pairs that provide additional user-defined
information about the exception.
HelpLink Gets or sets a link to the help file associated with this exception.
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a
specific exception.
InnerException Gets the Exception instance that caused the current exception.
Message Gets a message that describes the current exception.
Source Gets or sets the name of the application or the object that causes the
error.
StackTrace Gets a string representation of the frames on the call stack at the time the
current exception was thrown.
TargetSite Gets the method that throws the current exception.
---------------------------------------------------------------------------------------------------------------------------------------------------------
If we type in a numeric value for num1 and then an alphabetical character for
num2 , the exception is caught and displayed like this:
Please enter the first number:6
Please enter the second number:a
Input string was not in a correct format.
We enter 0 for the second number, we get a different description for the error:
Please enter the first number:7
Please enter the second number:0
Attempted to divide by zero.
Notice that two different types of exceptions are caught using the same Exception class. The
description of the exception is contained within the Message property of the Exception class.
We can use the ToString() method of the Exception class to retrieve more details about the
exception, such as the description of the exception as well as the stack trace.
However, there are cases where we would like to print our own custom error messages for the different types of exceptions. Using the preceding code, we would not be able to do that — we would
need a much finer way to catch the different types of possible exceptions.
To know the different types of exceptions that our program can cause (such as entering “ a” for num1 or
division by zero), we can set a breakpoint at a line within the catch block and try entering different values.
When an exception is raised during runtime, IntelliSense tells we the error and the type of the exception
raised.
If we are not sure what type of exception our program is going to raise during runtime, it is always
safe to use the base Exception class. If not — if the exception that is raised does not match the exception
we are trying to catch — a runtime error will occur. Here ’ s an example:

static void Main(string[] args)
{
int num1, num2, result;
try
{
Console.Write(“Please enter the first number:”);
num1 = int.Parse(Console.ReadLine());
Console.Write(“Please enter the second number:”);

num2 = int.Parse(Console.ReadLine());
result = num1 / num2;
Console.WriteLine(“The result of {0}/{1} is {2}”,
num1, num2, result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}

If a division - by - zero exception occurs (entering 0 for num2 ), the exception is caught. However, if we
enter an alphabetic character for num1 or num2 , a FormatException exception is raised. And because
we are only catching the DivideByZeroException exception, this exception goes unhandled and a
runtime error results.



Responses

Author: Varun Kumar    05 Oct 2009Member Level: Bronze   Points : 0



varun web security.doc
Author: Abhisek Panda    05 Oct 2009Member Level: Gold   Points : 0
Good post Muhammad Javed. Keep posting more in DNS.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Handling Exception in C#  .  Exception Handling in C#  .  Exception Class in C Sharp  .  Exception  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Automatic Properties in C Sharp
Previous Resource: Handling Multiple Exceptions In C#
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use