๐ŸŽ“ A1Learner
๐Ÿ”

C# Exceptions

An exception is an error object that a running program creates when something goes wrong. A try and catch pair lets the program answer the error and keep running.

Catch a Division Error

Dividing by zero throws a DivideByZeroException. The catch block prints a fixed line instead.

using System;

class Program
{
    static void Main(string[] args)
    {
        int total = 10;
        int parts = 0;
        try
        {
            int share = total / parts;
            Console.WriteLine(share);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Cannot divide by zero.");
        }
    }
}

Catch a Bad Index

The array has three items, so index 5 does not exist. The catch names IndexOutOfRangeException.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3 };
        try
        {
            Console.WriteLine(numbers[5]);
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Index out of range.");
        }
    }
}

Finally Always Runs

The catch prints first. The finally block then prints its line as well.

using System;

class Program
{
    static void Main(string[] args)
    {
        int total = 8;
        int parts = 0;
        try
        {
            int share = total / parts;
            Console.WriteLine(share);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Division failed.");
        }
        finally
        {
            Console.WriteLine("Always runs.");
        }
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            int number = Convert.ToInt32("abc");
            Console.WriteLine(number);
        }
        catch (FormatException)
        {
            Console.WriteLine("Not a number.");
        }
        finally
        {
            Console.WriteLine("Done checking.");
        }
    }
}

Key points

  • Try: the block that holds code that might fail.
  • Catch: the block that runs when the try block throws an exception.
  • A catch names the exception type it answers.
  • A catch for one type does not answer other types.
  • Finally: a block that runs after try and catch, whatever happened.
  • Code after a caught exception keeps running.

In this example, Convert.ToInt32 is asked to read the text "abc" as a number. The text is not a number, so a FormatException is thrown. The catch block prints "Not a number." The finally block runs after the catch and prints "Done checking."

Note

Each exception type has a name that says what went wrong, like DivideByZeroException.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

Which block runs after a try block whether or not an exception was thrown?