User-Defined Exceptions
You can create your own exceptions. User-defined exceptions must inherit from the Exception base class. We will create another separate class that inherits from the Exception base class. Create a new Console Application and name it UserDefinedExceptions. After the project is created, click the Add New Item button in the toolbar and browse for the Class template. Name the file NegativeNumberException.
using System;
namespace UserDefinedExceptions
{
class NegativeNumberException : Exception
{
public NegativeNumberException()
: base("The operation will result to a negative number.")
{
}
public NegativeNumberException(string message)
: base(message)
{
}
public NegativeNumberException(string message, Exception inner)
: base(message, inner)
{
}
}
}
Example 1 – NegativeNumberException Class
You can see in line 5 that our custom class inherits from the Exception class. As a convention, user-defined exception class names must be appended with the word “Exception” and it should define 3 constructors. The first one is the parameterless constructor, the second constructor accepts a string argument which defines the error message, and the third constructor accepts the error message, and the inner exception the caused the current exception.
Let’s try to use our very own exception class. In the Program.cs file, use the following codes.
using System;
namespace UserDefinedExceptions
{
class Program
{
public static void Main()
{
int firstNumber, secondNumber, difference;
Console.Write("Enter the first number: ");
firstNumber = Int32.Parse(Console.ReadLine());
Console.Write("Enter the second number: ");
secondNumber = Int32.Parse(Console.ReadLine());
difference = firstNumber - secondNumber;
try
{
if (difference < 0)
{
throw new NegativeNumberException();
}
}
catch (NegativeNumberException error)
{
Console.WriteLine(error.Message);
}
}
}
}
Example 2 – Using NegativeNumberException
Enter the first number: 10 Enter the second number: 11 The operation will result to a negative number.
Since yielding a negative number as a result will not issue any kind of exception, we need to manually throw it ourselves. We ask two values from the user (line 11-15). We then calculated the difference of the two (line 17). Inside the try block, we tested if the result of the operation is a negative number (line 21). If it is, then we throw a new instance of the NegativeNumberException class (line 23). This will then be caught by the catch block and show the error message (line 24-26).