๐ŸŽ“ A1Learner
๐Ÿ”
0 of 41 lessons completed

C# Throw

The throw statement creates an exception at a chosen point in the code. Code uses it to reject a value that breaks a rule.

Throw Without a Catch

CheckAge throws for an age under 18, and nothing catches it. The runtime prints the error and the program ends.

using System;

class Program
{
    static void CheckAge(int age)
    {
        if (age < 18)
        {
            throw new ArgumentException("Access denied. You must be 18 or older.");
        }
        Console.WriteLine("Access granted.");
    }

    static void Main(string[] args)
    {
        CheckAge(15);
    }
}

Catch a Thrown Exception

The same call now sits inside a try block. The catch prints the message stored in the exception.

using System;

class Program
{
    static void CheckAge(int age)
    {
        if (age < 18)
        {
            throw new ArgumentException("Access denied. You must be 18 or older.");
        }
        Console.WriteLine("Access granted.");
    }

    static void Main(string[] args)
    {
        try
        {
            CheckAge(15);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Throw a Built-In Exception

A count of zero would break the division ahead. The code throws a DivideByZeroException before dividing.

using System;

class Program
{
    static void Main(string[] args)
    {
        int count = 0;
        try
        {
            if (count == 0)
            {
                throw new DivideByZeroException();
            }
            Console.WriteLine(10 / count);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Count is zero.");
        }
    }
}

Example

using System;

class Program
{
    static void CheckScore(int score)
    {
        if (score < 0 || score > 100)
        {
            throw new ArgumentException("Score must be between 0 and 100.");
        }
        Console.WriteLine("Score accepted.");
    }

    static void Main(string[] args)
    {
        try
        {
            CheckScore(120);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.WriteLine("Program continues.");
    }
}

Key points

  • Throw: a statement that creates an exception and stops the current path.
  • Write new before the exception type to create the exception object.
  • A text argument becomes the message of the exception.
  • An exception that nothing catches ends the program.
  • The runtime prints the exception type and its message for an uncaught exception.
  • A try and catch pair can catch a thrown exception.
  • The Message property of a caught exception holds its text.

In this example, CheckScore is called with 120. The score is above 100, so CheckScore throws an ArgumentException. The catch block prints the message from the exception. The last line of Main then prints, so "Program continues." follows the message.

Note

Throwing is for values a program cannot work with. Normal checks still belong in if statements.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a thrown exception is not caught anywhere?