Font size
Site color
Preskočiť na hlavný obsah

Custom Exceptions

To best tailor the exception handling system to your needs, you can create your own custom exceptions by inheriting from the Exception class and then use throw to throw them.

Suppose the task is to create a MissingUserInputException exception that should be thrown when the user does not enter the student's age or enters whitespace (space) in the example from the previous lessons. The MissingUserInputException class and the main program can look like this:

using System;

class MissingUserInputException : Exception
{
    public MissingUserInputException(string message) : base(message) { }
}

class Program
{
    static void Main()
    {
        Console.Write("How old are you (integer): ");
        try
        {
            string num = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(num))
            {
                throw new MissingUserInputException("You must enter the age!");
            }
            else
            {
                int age = int.Parse(num);
                Console.WriteLine("You are " + age + " years old.");
            }
        }
        catch (FormatException e)
        {
            Console.WriteLine("You did not enter an integer in the correct format!");
            Console.WriteLine("An example of a correct integer format is: 17");
            Console.WriteLine("Error details: " + e);
        }
        catch (OverflowException e)
        {
            Console.WriteLine("The integer must be in the range from -2147483648 to 2147483647.");
            Console.WriteLine("An example of an integer within allowed bounds is: 17");
            Console.WriteLine("Error details: " + e);
        }
        catch (Exception e)
        {
            Console.WriteLine("An unexpected error occurred.");
            Console.WriteLine("Error details: " + e);
        }
    }
}
Ana

When the user does not enter the student's age or enters whitespace, console execution will look like this:

How old are you (integer):
An unexpected error occurred.
Error details: MissingUserInputException: You must enter the age!
   at Program.Main() in C:\ConsoleApp\Program.cs:line 18