WeCodeAcademy

C# Exceptions

ExampleC#
using System;

class Program
{
    static int Divide(int a, int b)
    {
        if (b == 0) throw new ArgumentException("Cannot divide by zero");
        return a / b;
    }

    static void Main()
    {
        try
        {
            Console.WriteLine(Divide(10, 2));
            Console.WriteLine(Divide(1, 0));
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
        finally
        {
            Console.WriteLine("done");
        }
    }
}
Output
5
Error: Cannot divide by zero
done
Quick check

Which block always runs after try/catch?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.