Skip to content

Exceptions

The Course
•
25 min study

An exception is C#'s way of reporting that something couldn't be done. It stops the current code and travels up through the calling methods, looking for something that can handle it. If nothing does, the program crashes with the message you've seen in earlier lessons.

try and catch

Code that might fail goes in a try block. A catch block names the type of exception it can deal with. When an exception happens, the rest of the try block is skipped and the matching catch runs. After that, the program carries on as normal.

What gets skipped? C#
var minutes = new List<int> { 25 };

try
{
    Console.WriteLine(minutes[0]);
    Console.WriteLine(minutes[5]);
    Console.WriteLine("Never printed");
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("No such session");
}

Console.WriteLine("Carrying on");
Check your prediction
Text
25
No such session
Carrying on

Several catch blocks can follow one try, and each handles a different type. Giving the exception a name, as in catch (FormatException e), lets you read e.Message. A finally block runs whether or not anything failed, which suits clean-up work.

Different failures, different handling C#
Console.WriteLine(Divide("10", "2"));
Console.WriteLine(Divide("10", "0"));
Console.WriteLine(Divide("ten", "2"));

static string Divide(string top, string bottom)
{
    try
    {
        return (int.Parse(top) / int.Parse(bottom)).ToString();
    }
    catch (FormatException e)
    {
        return $"Bad number: {e.Message}";
    }
    catch (DivideByZeroException)
    {
        return "Cannot divide by zero";
    }
    finally
    {
        Console.WriteLine("Attempt finished");
    }
}
Check your prediction
Text
Attempt finished
5
Attempt finished
Cannot divide by zero
Attempt finished
Bad number: The input string 'ten' was not in a correct format.

The finally line prints before each result, because Console.WriteLine can only print after Divide has completely finished.

Throwing your own

throw new SomeException("message") raises an exception yourself. Use it when your method has been asked to do something that it can't do, and the caller has made a mistake. ArgumentException and ArgumentOutOfRangeException are for bad arguments, and InvalidOperationException means the object isn't in a state where this call makes sense.

A broken rule stops the method C#
try
{
    Console.WriteLine(Pace(100, 4));
    Console.WriteLine(Pace(100, 0));
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine($"Problem: {e.ParamName}");
}

static int Pace(int minutes, int days)
{
    if (days < 1)
    {
        throw new ArgumentOutOfRangeException(nameof(days), "must be at least 1");
    }
    return minutes / days;
}
Check your prediction
Text
25
Problem: days

nameof(days) produces the text days. If you later rename the parameter, the compiler keeps the two in step.

Which should you use?

You now have three ways of reporting a problem. The choice depends on how normal the problem is.

  • Expected and common: bad input, a missing dictionary key. Return false or null, as TryParse does. The caller must handle it, and it's part of normal work.
  • A mistake by the calling code: an impossible argument, or a call at the wrong time. Throw an exception. Something needs fixing, so it should be loud.
  • Something outside your control: a file that's gone, a network failure. Exceptions again, and catch them where you can do something useful about them.

Avoid catch (Exception) around large blocks of code. It also catches your own bugs, and turns a loud, useful crash into a program that silently does the wrong thing. Catch the specific types that you know how to recover from.

Your turn

Exercise

Load sessions safely

Write ParseMinutes(string text), which uses int.Parse and returns the number, and throws ArgumentOutOfRangeException when the value is below 1. Then write TotalMinutes(List<string> values), which calls it for each entry and catches both FormatException and ArgumentOutOfRangeException, counting those entries as skipped. It should print Skipped: ten or Skipped: -5 for each bad value and return the total of the good ones.

For the entries 25, ten, -5 and 40, print those two skip lines and then Total: 65.

Your workspace C#
var values = new List<string> { "25", "ten", "-5", "40" };
Console.WriteLine(values.Count);
Hint 1: the idea

The try block belongs inside the loop. If it were around the whole loop, the first bad entry would end all of the processing.

Hint 2: a first step

Write ParseMinutes first and call it once in a try, checking that ten reaches your catch.

Show one solution
C#
var values = new List<string> { "25", "ten", "-5", "40" };
Console.WriteLine($"Total: {TotalMinutes(values)}");

static int ParseMinutes(string text)
{
    int minutes = int.Parse(text);
    if (minutes < 1)
    {
        throw new ArgumentOutOfRangeException(nameof(text), "must be at least 1");
    }
    return minutes;
}

static int TotalMinutes(List<string> values)
{
    int total = 0;
    foreach (string value in values)
    {
        try
        {
            total += ParseMinutes(value);
        }
        catch (FormatException)
        {
            Console.WriteLine($"Skipped: {value}");
        }
        catch (ArgumentOutOfRangeException)
        {
            Console.WriteLine($"Skipped: {value}");
        }
    }
    return total;
}
Text
Skipped: ten
Skipped: -5
Total: 65

The try is inside the loop, around one value. If it were around the whole loop, the first bad value would end the loop, and 40 would never be added. ParseMinutes throws for both problems and leaves the decision to its caller, which here chooses to skip and carry on.

Rewrite TotalMinutes with int.TryParse and no exceptions at all. Which version is easier to read? For input validation like this, most C# programmers would pick TryParse, and that's what your planner will use.

Was this article helpful?

Your response is saved on this device.