Handling Exceptions in C#


Exceptions are errors that may occur duringthe run-time of a program. Exception handling, thus, becomes anintegral part of programming. In C#, exceptions are handled via theException base class. You can also create your own Exception class but,which will, necessarily, derive from the base, inbuilt Exception class.

An exception is, for example, a "divide byzero operation", which will result in a faulty or a needless result andhence, needs to be handled in a program. An exception can also be,"IndexOutOfBounds", which arises out when your program tries to accessa non-existent element in an array say, 101, in an array of max size100. There are many such inbuilt exceptions that are handled by theException base class but, since logic is about possibilities, thepossibility of an unhandled exception may arise and to know how tocreate your own exception class to handle such a calamity is thepurpose of this article.

The following is a program that defines my own Exception class.

using System;
public class MyException:Exception
{
public string s;
public MyException():base()
{
s=null;
}
public MyException(string message):base()
{
s=message.ToString();
}
public MyException(string message,Exception myNew):base(message,myNew)
{
s=message.ToString();// Stores new exception message into class member s
}
public static void Test()
{
string str,stringmessage;
bool flag=false;
stringmessage=null;
char ch=' ';
int i=0;
Console.Write("Please enter some string (less than 27 characters) – ");
str=Console.ReadLine();
try{
ch=str[i];
while (flag==false)
{
if (ch=='\r')
{
flag=true;
}
else{
ch=str[i];
i++;
}
}
}
catch(Exception e){
flag=true;
}

if (i>27)
{
stringmessage="You cannot enter more than 27 characters !";
throw new MyException(stringmessage);
}
}
public static void Main()
{
try
{
Test();
}
catch(MyException e)
{
Console.WriteLine(e.s);
}
}
}

The above program creates a new exceptionclass called MyException, which derives from the base Exception class.The class has three constructors – one, default and two overloadedconstructors. The intention is simple – to be able to overload aconstructor of the base class, the base class' default or existingconstructors must be implemented in the deriving class and thenoverload the relevant constructor. But, the real purpose of the classis to handle an exception – if the user enters more than 27 characters,then a message prompting the user of the error is to be displayed.Although, this is not really an exception, such an instance is actuallycalled Validation of data but, for want of an example, such anoccurrence has been used for exception handling. The new exceptionMyException is thrown from the Test() method and the message – "Youcannot enter more than 27 characters !" – is passed to the class, whichis retrieved by the catch block in the Main() method !

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!