Tamanho da letra
Cor do site
Ir para o conteúdo principal

Throwing exceptions

When you want to signal that an error or unexpected condition has occurred, you can use throw to throw a new exception. Most often, this will be one of the predefined exceptions such as ArgumentException, InvalidOperationException, etc.

For example, suppose the task is to create a method for validating the age of students in your class. Although the main program already verified that the entered age is not a string and does not exceed the bounds defined by the type, this method should verify whether the entered age is acceptable for a 3rd-year student. Let an acceptable age be 16, 17, 18, or 19, and an unacceptable age be less than 16 or greater than 19, and let the method be called in the program from the previous lesson:

using System;

class Program
{
    static void ValidateAge(int age)
    {
        if (age < 16 || age > 19)
        {
            throw new ArgumentException("Number must be in the range from 16 to 19.");
        }
        Console.WriteLine("The entered age is valid.");
    }

    static void Main()
    {
        Console.Write("How old are you (integer): ");
        try
        {
            int age = int.Parse(Console.ReadLine());
            ValidateAge(age);
            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);
        }
        finally
        {
            Console.WriteLine("End of program!");
        }
    }
}
5

If the user enters an unacceptable age for a 3rd-year student, the console execution will look like this:

How old are you (integer): 10
An unexpected error occurred.
Error details: System.ArgumentException: Number must be in the range from 16 to 19.
   at Program.ValidateAge(Int32 age) in C:\ConsoleApp\Program.cs:line 10
   at Program.Main() in C:\ConsoleApp\Program.cs:line 20
End of program!

Since the thrown exception is neither FormatException nor OverflowException, it is caught and handled only in the third catch block.

What would happen if exceptions were not handled in the main program…

using System;

class Program
{
    static void ValidateAge(int age)
    {
        if (age < 16 || age > 19)
        {
            throw new ArgumentException("Number must be in the range from 16 to 19.");
        }
        Console.WriteLine("The entered age is valid.");
    }

    static void Main()
    {
        Console.Write("How old are you (integer): ");
        int age = int.Parse(Console.ReadLine());
        ValidateAge(age);
        Console.WriteLine("You are " + age + " years old.");
        Console.WriteLine("End of program!");
    }
}

…and the user enters an unacceptable age for a 3rd-year student:

How old are you (integer): 10

Unhandled Exception: System.ArgumentException: Number must be in the range from 16 to 19.
   at Program.ValidateAge(Int32 age) in C:\ConsoleApp\Program.cs:line 9
   at Program.Main() in C:\ConsoleApp\Program.cs:line 18

The program crashed! The exception was thrown, but it was not caught and handled!