Custom Exception Classes - C#:

Started by sukishan, Jul 11, 2009, 03:04 PM

Previous topic - Next topic

sukishan

Custom Exception Classes - C# Tutorial: 

Some larger projects might have a requirement of creating their own custom exception classes. Let us try to create class that validates email address. It will validate for the ?@? symbol. Please have a look on the following piece of code:


--------------------------------------------------------------------------------

//Sample code for C# .Net Exception tutorial - validates an email address

public class TextException : Exception
{

public TextException() : base()

{
}

public TextException(string message) : base(message)
{

}

}

public class MailValidator
{

MailValidator()
{

}

private static char symbol = '@';

public static void TestEnteredMail(string mailAddress)
{

if(mailAddress.IndexOf(symbol)==-1)
{

Console.WriteLine("The string entered is not a valid email address");

throw(new TextException());

}

}

}


--------------------------------------------------------------------------------

   Here were created a C# .Net TextException class that inherits from System.Exception class of .NET class library. Actually it does nothing, but there is an additional class MailValidator. It has TestEnteredMail method that raises a TextException. Now look at usage of it in Main function.


--------------------------------------------------------------------------------

try
{

MailValidator.TestEnteredMail(Console.ReadLine());

}
catch(TextException)
{

Console.WriteLine("Exception was passed");

}
A good beginning makes a good ending