You can throw exceptions anywhere in the program to artificially create an occurrence of an error. Additionally, you can create custom messages if you don’t like the default message of an exception. The following program shows you an example.

using System;
 
namespace ThrowingExceptions
{
    class Program
    {
        public static void Main()
        {
            int firstNumber, secondNumber, result;
 
            Console.Write("Enter the first number: ");
            firstNumber = Int32.Parse(Console.ReadLine());
 
            Console.Write("Enter the second number: ");
            secondNumber = Int32.Parse(Console.ReadLine());
 
            try
            {
                if (secondNumber == 0)
                {
                    throw new DivideByZeroException();
                }
                else
                {
                    result = firstNumber / secondNumber;
                }
            }
            catch (DivideByZeroException error)
            {
                Console.WriteLine(error.Message);
            }
        }
    }
}

Example 1 – Manually Throwing Exceptions

Enter the first number: 10
Enter the second number: 0
Attempted to divide by zero.

In line 19, we used the throw keyword followed by an instance of an exception class. We have just gone straight to creating the instance and throwing it in just one line. For example, you can create an object first and then throw it.

DivideByZeroException error = new DivideByZeroException();

throw error;

You can also give your own error message by using an overloaded constructor of the Exception class which accepts a string as the error message.

throw new DivideByZeroException("Cannot divide by zero!");

This will modify the default error message stored in the Message property. Throwing exceptions are mostly used when a certain code will not naturally yield an error, but you want to consider it an error anyways. The next lesson will show you something like that.