In that tutorial, at the end you saw how to throw your own exceptions. Here will do the same thing, but a bit more complicated because now you'll be able to customize the exception.
Create a new Console Application project named customExceptions in Microsoft Visual Studio .NET.
First we'll have to create the class derived from System.ApplicationException:
// Creating the class derived from System.ApplicationException
public class NumberZeroException : System.ApplicationException
{
// The constructor that takes msg as a parameter
public NumberZeroException(string msg) : base(msg)
{
}
}
As you can see, it's nothing more than a class derived from System.ApplicationException with a constructor that takes the msg as a parameter.
Here's Class1 where we actually throw the exception if the user enters '0'.
class Class1
{
[STAThread]
static void Main(string[] args)
{
// Prompt the user to enter an integer
Console.WriteLine("Please input an integer: ");
// Try this block of code
try
{
// Store the input in x
int x = Convert.ToInt32(Console.ReadLine());
// If the number entered is 0...
if(x == 0)
{
// ...throw our custom exception with the following message parameter
throw new NumberZeroException("You are not allowed to enter number 0");
by Shankar on Tuesday, August 7th 2007 at 08:46 AM
Thank you, it helped me...
by Coralys.com on Friday, August 1st 2008 at 07:16 AM
A very simplistic approach that does not cover proper custom exception "manufacturing". In fact if you read Microsoft documentation you will see that they say you must derive your custom exceptions from System.Exception and NOT from System.ApplicationException.
You also missed here the default constructors and the serialization constraints.
But well, better than nothing at all.
by Structed on Tuesday, February 17th 2009 at 04:41 AM
Sorry to say that, but that's absolutely useless.
You can learn even more if you just use the Exception-Snippet in Visual Studio (Express)...
by software dev on Thursday, December 10th 2009 at 04:53 PM
"Where there is a will, there is a way"
If you have been in software development for a while, you would agree that criticizing any code block can be easy. Let's be a little positive and appreciate the efforts of the author.
by Structed on Friday, December 11th 2009 at 03:15 AM
I did not meant the code being bad or unclean.
But you are right. It's good to have someone telling the new developers directions.
Sorry for this post above. I have matured myself :-)