Following an Exception: Stack Traces and Catching Higher Up

Read a stack trace to find the line where an exception started and the calls that led there, catch it in the method that knows what to do, and wrap it with a clearer message and the facts the catcher needs.

Apprentice · C# · Updated

By

After this lesson you can

  • Read a stack trace to find the method and line where an exception started, and the calls that led there
  • Catch an exception in a method further up the call stack, and say which code it skips and which variables catch can see
  • Wrap an exception with a clearer message, its InnerException and Data, and read those properties where it's caught

Key takeaways

  • A stack trace lists the methods an exception passed through, newest call first. The first line with your file name and a line number is where your code was when it went wrong.
  • An exception travels up the call stack, from the method that threw it to the methods that called it, skipping the rest of each one until a matching catch handles it.
  • Catch an exception in the method that knows what to do about it, which is often a caller several calls up, not the method where it started.
  • A variable declared inside a try block can't be seen in its catch block or after it. Declare it before the try.
  • To add facts, throw a new exception with a clearer message, the original as its InnerException, and extra values in its Data.

The school's office runs your grade report, and it crashes. All they can send you is the screen full of red text it printed. That text is a stack trace, and it's the best clue you'll get: it names the line where things went wrong and every method call that led there. Learning to read it, and to decide where an exception should be caught, is what turns "it crashed" into a fix that takes five minutes.

In Exceptions in C# you caught an exception right where it happened. Real programs are methods calling methods, and the method that finds a problem is often not the one that knows what to do about it.

Methods calling methods: the call stack

Here is a small grade reader. The top-level code calls LoadGpas, and LoadGpas calls ParseGpa once for each line. Save it as grades.cs and run it with dotnet run grades.cs:

string[] lines = { "Emily,3.91", "Sarah,3.31", "David,n/a" };
List<decimal> gpas = GradeReader.LoadGpas(lines);
Console.WriteLine(quot;Read {gpas.Count} grades");

static class GradeReader
{
    public static List<decimal> LoadGpas(string[] lines)
    {
        List<decimal> gpas = new List<decimal>();
        foreach (string line in lines)
        {
            gpas.Add(ParseGpa(line));
        }
        return gpas;
    }

    static decimal ParseGpa(string line)
    {
        string[] columns = line.Split(',');
        return decimal.Parse(columns[1]);
    }
}
Unhandled exception. System.FormatException: The input string 'n/a' was not in a correct format.

That's the first line of what it prints. To know which code was running, C# keeps a list of the calls that are still in progress: the top-level code is waiting for LoadGpas to finish, and LoadGpas is waiting for ParseGpa. That list is the call stack. Think of a stack of trays in a cafeteria: each new call puts a tray on top, and when a method finishes, its tray comes off, and the method underneath carries on where it left off.

Reading a stack trace

When the exception isn't caught, C# prints the call stack as it was at that moment. Here is the whole of it, with the folder shortened to C:\bootcamp:

Unhandled exception. System.FormatException: The input string 'n/a' was not in a correct format.
   at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
   at System.Number.ParseDecimal[TChar](ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Decimal.Parse(String s)
   at GradeReader.ParseGpa(String line) in C:\bootcamp\grades.cs:line 20
   at GradeReader.LoadGpas(String[] lines) in C:\bootcamp\grades.cs:line 12
   at Program.<Main>$(String[] args) in C:\bootcamp\grades.cs:line 2

Read it from the top:

  1. The first line is the exception's type, System.FormatException, and its message: the text 'n/a' isn't a number.
  2. Each at line is one call, newest first. decimal.Parse was running when it went wrong, inside ParseGpa, inside LoadGpas, inside the top-level code (Program.<Main>$ is the name C# gives your top-level statements).
  3. Lines that start with System. are .NET's own code. They have no file name, and the bug is almost never there.
  4. The first line with your file and a line number is where your code was: grades.cs:line 20, the decimal.Parse(columns[1]) in ParseGpa. The lines under it tell you how the program got there: line 12 called ParseGpa, and line 2 called LoadGpas.

So the fix starts at line 20, and the question to ask is "where did 'n/a' come from?" The lines below answer it: from the third line of lines, passed in by line 2.

The debugger shows the same list while it runs. Press F5 in Visual Studio and, when the exception stops the program, open Debug > Windows > Call Stack (Ctrl+Alt+C). The newest call is at the top, as in the trace. Double-click a row to jump to that method's line and see its variables in the Locals window: click LoadGpas, and line shows "David,n/a".

The exception travels up the call stack

People say an exception travels up the call stack: from the method that threw it up to the method that called it, then up to that one's caller, the way a problem at a store goes from the clerk to the manager to the owner until someone deals with it.

Three boxes stacked from top to bottom, Top-level code, LoadGpas and ParseGpa, with arrows going down that say calls; a red FormatException arrow goes back up from ParseGpa, past LoadGpas, whose line Finished reading is skipped, and stops at the catch in the top-level code

So you don't have to catch an exception in the method where it happens. Catch it in the method that knows what to do about it. ParseGpa doesn't know which file it's reading or who to tell, but the top-level code does: it can tell the office which file has a bad line. This version catches there, two calls up from decimal.Parse:

string[] lines = { "Emily,3.91", "David,n/a", "Sarah,3.31" };

try
{
    List<decimal> gpas = GradeReader.LoadGpas(lines);
    Console.WriteLine(quot;Read {gpas.Count} grades");
}
catch (FormatException ex)
{
    Console.WriteLine(quot;The grade file has a bad line: {ex.Message}");
}

Console.WriteLine("The program carries on");

static class GradeReader
{
    public static List<decimal> LoadGpas(string[] lines)
    {
        List<decimal> gpas = new List<decimal>();
        foreach (string line in lines)
        {
            Console.WriteLine(quot;Reading {line}");
            gpas.Add(ParseGpa(line));
        }
        Console.WriteLine("Finished reading");
        return gpas;
    }

    static decimal ParseGpa(string line)
    {
        string[] columns = line.Split(',');
        return decimal.Parse(columns[1]);
    }
}
Reading Emily,3.91
Reading David,n/a
The grade file has a bad line: The input string 'n/a' was not in a correct format.
The program carries on

Look at what didn't print. When decimal.Parse threw, the rest of ParseGpa was skipped, then the rest of LoadGpas: the loop never reached Sarah, Finished reading never printed, and return gpas never ran. In the top-level code, Read ... grades was skipped too, because LoadGpas never returned a list to count. The program picked up again in the first catch that matched, and then carried on after it.

A variable inside try stays inside try

A try block is a block like any other: a variable declared inside its curly braces only exists inside them. The catch block and the code after it can't see it:

try
{
    decimal gpa = decimal.Parse("3.91");
}
catch (FormatException)
{
    Console.WriteLine("That isn't a GPA");
}

Console.WriteLine(quot;GPA: {gpa}");
error CS0103: The name 'gpa' does not exist in the current context

When the code after the try needs the value, declare the variable before the try, with a value it keeps if the try fails, and set it inside:

decimal gpa = 0;

try
{
    gpa = decimal.Parse("n/a");
}
catch (FormatException)
{
    Console.WriteLine("That isn't a GPA, so it stays 0");
}

Console.WriteLine(quot;GPA: {gpa}");
That isn't a GPA, so it stays 0
GPA: 0

What an exception object holds

An exception is an object, and Message is only one of its properties. These are the ones you'll use:

Property What it holds
Message The description of what went wrong
StackTrace The list of calls, as text: the at lines from the trace above
InnerException The exception that caused this one, when it was wrapped (below), or null
Data Extra facts the thrower added, looked up by a name, such as ex.Data["LineNumber"]
ParamName On an ArgumentException: the name of the parameter whose value wasn't allowed

ex.GetType().Name gives the exception's type as text. Here is an ArgumentException read three ways:

try
{
    SetGpa(5.2m);
}
catch (ArgumentException ex)
{
    Console.WriteLine(quot;Type: {ex.GetType().Name}");
    Console.WriteLine(quot;ParamName: {ex.ParamName}");
    Console.WriteLine(quot;Message: {ex.Message}");
}

void SetGpa(decimal gpa)
{
    if (gpa < 0 || gpa > 4)
    {
        throw new ArgumentException("A GPA is from 0.00 to 4.00.", nameof(gpa));
    }
    Console.WriteLine(quot;GPA set to {gpa}");
}
Type: ArgumentException
ParamName: gpa
Message: A GPA is from 0.00 to 4.00. (Parameter 'gpa')

Wrapping an exception with the facts the catcher needs

The message The input string 'n/a' was not in a correct format is true, but the office can't act on it: which line? ParseGpa doesn't know the line number, but LoadGpas does, because it's the one counting. So LoadGpas can catch the exception on its way up, and throw a new one that says more:

string[] lines = { "Emily,3.91", "David,n/a", "Sarah,3.31" };

try
{
    GradeReader.LoadGpas(lines);
}
catch (FormatException ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(quot;Line number: {ex.Data["LineNumber"]}");
    Console.WriteLine(quot;Caused by: {ex.InnerException?.Message}");
}

static class GradeReader
{
    public static List<decimal> LoadGpas(string[] lines)
    {
        List<decimal> gpas = new List<decimal>();
        int lineNumber = 0;
        foreach (string line in lines)
        {
            lineNumber++;
            try
            {
                gpas.Add(ParseGpa(line));
            }
            catch (FormatException ex)
            {
                FormatException clearer = new FormatException(quot;Line {lineNumber}: can't read '{line}'", ex);
                clearer.Data["LineNumber"] = lineNumber;
                throw clearer;
            }
        }
        return gpas;
    }

    static decimal ParseGpa(string line)
    {
        string[] columns = line.Split(',');
        return decimal.Parse(columns[1]);
    }
}
Line 2: can't read 'David,n/a'
Line number: 2
Caused by: The input string 'n/a' was not in a correct format.

Three things customize the new exception:

  • A clearer message, the first argument: it names the line and its text.
  • The original as its InnerException, the second argument (ex): nothing is lost, and its own stack trace still points at decimal.Parse.
  • An entry in Data: clearer.Data["LineNumber"] = lineNumber adds a fact the catcher can read by name, without picking it out of the message.

Then throw clearer; sends it on up, and the top-level code catches it like any other FormatException. Notice lineNumber is declared before the try, so the catch can use it.

Testing, debugging and handling exceptions: three different jobs

These three come up together, and each does a different job for you as a developer:

Job The question it answers Its tools
Testing Is something wrong? Before your users find out Unit tests that check the answers, such as the exercises' MSTest tests
Debugging Where, and why? The stack trace, breakpoints, stepping, the Locals and Call Stack windows
Exception handling What should the program do when something outside its control goes wrong while it runs, such as a missing file or a bad line? try, catch, finally and throw

A bug in your own code is found by testing and fixed after debugging, not hidden with a catch. A file with a bad line in it isn't a bug in your code; it's the world being messy, and that's what exception handling is for.

Do it: report the average, or the bad line

The grade book shows the class's average GPA on the office's screen. AverageGpa works out the average from lines such as "Emily,3.91", and when a line's GPA isn't a number, it throws a FormatException whose message names the line, such as Line 2: can't read 'David,n/a'. Right now that exception crashes the screen. Catch it two calls up, in the method that builds the text the office sees.

The method gets one value:

  • lines: the class's lines, each a name, a comma and a GPA, a string[] ({ "Emily,3.91", "Sarah,3.31" }). It always holds at least one line.

AverageGpa and ParseGpa are written for you, below your method. Don't change them.

For example:

lines What happens Returns
{ "Emily,3.91", "Sarah,3.31" } (3.91 + 3.31) / 2 = 3.61 "Average GPA: 3.61"
{ "Emily,3.91", "David,n/a", "Sarah,3.31" } AverageGpa throws a FormatException with the message Line 2: can't read 'David,n/a' "Can't work out the average. Line 2: can't read 'David,n/a'"

Your job: finish the method AverageReport(string[] lines) so it returns a string.

  • Call AverageGpa(lines). When it returns, give back Average GPA: and the average with two decimal places.
  • When it throws a FormatException, catch it and give back Can't work out the average. (with one space after the period) followed by the exception's message.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

A stack trace tells you where to look, newest call first. An exception climbs the call stack until a catch that matches, so catch it where your code knows what to do, and give it a message and facts that let the next person fix the problem in minutes.

Key terms