Your program is going to fail, and not just once. It happens to everyone who writes code, every day. The difference between being stuck for an hour and fixing it in two minutes usually comes down to one thing: reading the error message calmly before you touch the code.
In this chapter you’ll learn to tell the two kinds of errors apart, read an exception line by line, catch errors with try/catch, and use the VS Code debugger to watch your program while it runs. It’s the last chapter of Part 1.
Two kinds of errors
You saw the first one in chapter 1: the compiler error. Before your program runs, .NET checks all of it. If something doesn’t make sense, it refuses to build it and nothing runs. Create a project with dotnet new console -n Errors and try this in Program.cs:
int age = "twenty";
Console.WriteLine(age);
.../Program.cs(1,11): error CS0029: Cannot implicitly convert type 'string' to 'int' [.../Errors.csproj]
The build failed. Fix the build errors and run again.
Line 1, column 11: right where "twenty" starts. You’re trying to store text in an int variable, and the compiler warns you before anything happens.
The second kind is the exception, an error that happens while the program runs. The code compiles fine, but at some point something happens that the program can’t handle:
int age = int.Parse("abc");
Console.WriteLine(age);
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
at System.Int32.Parse(String s)
at Program.<Main>$(String[] args) in .../Program.cs:line 1
As far as the compiler is concerned, this is fine: int.Parse takes a string and returns an int. The problem only shows up when it runs and finds out that "abc" isn’t a number. That’s why the program stopped dead and the second line never ran.
Compiler errors are the good ones, even if it doesn’t feel that way: you find them yourself, on your own computer, before anyone uses the program. Exceptions can hit the person using it.
How to read an exception
That block of text is scary the first time, but it has fixed parts.
The first line holds the most important information. Unhandled exception means nobody caught it, so the program ended. Then comes the exception type, System.FormatException, and the message, which here says the text 'abc' isn’t in a correct format. Often the message alone tells you what happened.
The lines that start with at are the stack trace. It’s the path the program took to reach the error, and you read it top to bottom: the top is where it blew up, and each line below is whoever called the line above. Lines that start with System. are .NET’s own code; you don’t need to understand them. Look for the first line that mentions your file. Program.<Main>$ is the internal name C# gives the code in your Program.cs, and line 1 is the exact line.
With methods the path is easier to see. This program uses a local function like the ones in chapter 6:
string[] days = { "Monday", "Tuesday", "Wednesday" };
Console.WriteLine(DayAtPosition(days, 1));
Console.WriteLine(DayAtPosition(days, 5));
static string DayAtPosition(string[] list, int position)
{
return list[position];
}
Tuesday
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<<Main>$>g__DayAtPosition|0_0(String[] list, Int32 position) in .../Program.cs:line 7
at Program.<Main>$(String[] args) in .../Program.cs:line 3
The first call worked and printed Tuesday. The second one failed. The top line says it blew up inside DayAtPosition, on line 7. The line below says DayAtPosition was called from line 3. The odd name with <<Main>$>g__ is how C# names a local function internally; what matters is the method name in the middle.
Notice that the error happened on line 7, but line 3 is to blame, because it asked for position 5 of a three-element array. That’s why the full stack trace is useful: the problem isn’t always where things blew up.
The exceptions you’ll see most
FormatException: you already know this one. It shows up when you convert text that isn’t in the expected format, like int.Parse("abc").
IndexOutOfRangeException: you asked for a position the array doesn’t have.
int[] numbers = { 10, 20, 30 };
Console.WriteLine(numbers[3]);
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in .../Program.cs:line 2
Three elements have positions 0, 1 and 2. Position 3 doesn’t exist. This one shows up a lot in a for loop that uses <= where < belonged.
KeyNotFoundException: you looked up a key that isn’t in a dictionary.
var prices = new Dictionary<string, decimal>();
prices.Add("apple", 0.75m);
Console.WriteLine(prices["pear"]);
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'pear' was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Program.<Main>$(String[] args) in .../Program.cs:line 3
The message tells you which key was missing. If you don’t know whether the key exists, use ContainsKey or TryGetValue, which you saw in chapter 5.
NullReferenceException: you tried to use something that’s empty. In C#, null means “there’s nothing here”. When you create an array of strings with new string[3], you get three slots, but all three are null until you put something in them:
string[] names = new string[3];
Console.WriteLine(names[0].Length);
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Program.<Main>$(String[] args) in .../Program.cs:line 2
.Length tells you how many characters a string has, but there’s no string in names[0]. The message doesn’t say which variable was empty, so you have to look at the line the stack trace points to and ask what on that line could be null. You’ll see this exception more once we get to objects.
Catch the exception with try/catch
You can tell C# “try this, and if it fails in this particular way, do this instead”. That’s what try/catch is for:
try
{
int age = int.Parse("abc");
Console.WriteLine($"You are {age} years old.");
}
catch (FormatException ex)
{
Console.WriteLine("That's not a number.");
Console.WriteLine($"Details: {ex.Message}");
}
Console.WriteLine("The program keeps running.");
That's not a number.
Details: The input string 'abc' was not in a correct format.
The program keeps running.
The code inside try runs normally. When int.Parse throws the exception, C# jumps straight to the catch for that type; the line that prints the age never runs. ex is the caught exception, and ex.Message is the same message that used to show up in the terminal. After the catch, the program continues.
Put the exception type you expect in the catch. There is a catch (Exception) that catches anything, but if you use it without thinking, you’ll hide errors you should be seeing and fixing.
For user input, use TryParse
A person typing letters where you asked for a number isn’t unusual: it will happen. You don’t need try/catch for that. You already know the tool from chapter 3:
string text = "abc";
if (int.TryParse(text, out int number))
{
Console.WriteLine($"I read the number {number}.");
}
else
{
Console.WriteLine($"'{text}' is not a valid number.");
}
'abc' is not a valid number.
In a real program, text would come from Console.ReadLine(); here it’s fixed so you can see the result. TryParse doesn’t throw: it tells you with a bool whether the conversion worked. My rule is simple. If the failure is something normal you can check beforehand, like what the user types or a key in a dictionary, check it with TryParse, ContainsKey or an if. Save try/catch for what you can’t check in advance.
The VS Code debugger
Sometimes the program doesn’t blow up, but it does the wrong thing. That’s where the debugger is your best tool: it lets you pause the program on a line and look at the value of every variable. With C# Dev Kit you already have it. These steps come from the official VS Code documentation.
- Set a breakpoint. Open
Program.csand click the left margin next to a line number, or put the cursor on the line and press F9. A red dot appears. That’s where the program will pause. - Start with F5. With
Program.csopen, press F5. The debugger finds your project and runs it. You can also use the button in the upper-right corner of the editor, Debug project associated with this file, or start from the Run and Debug view in the side bar. - Look at the variables. When the program reaches the breakpoint, it pauses and the line is highlighted. That line hasn’t run yet. In the Run and Debug view, the VARIABLES section shows the variables and their values. You can also hover over a variable in the editor to see what it holds.
- Watch expressions. In the WATCH section, click + and type a variable or an expression, like
sum / grades.Length. VS Code evaluates it every time the program pauses. - Step through. F10 (Step Over) runs the current line and stops at the next one. F11 (Step Into) goes into the method called on that line, which is useful with your own functions. Shift+F11 (Step Out) finishes the current method and goes back to its caller. F5 keeps running until the next breakpoint, and Shift+F5 stops the session.
What your program prints with Console.WriteLine shows up in the Debug Console panel. On some Macs, the F keys only work if you hold down the fn key.
Before you ask for help
When something fails, go in this order. First, read the whole first line of the error without skipping anything. Second, find the first line in the stack trace that mentions your file and go to that line. Third, if you still don’t see it, set a breakpoint before that line and look at the values.
If that doesn’t do it, explain the code out loud, line by line. It can be to a rubber duck on your desk; that’s why it’s called rubber duck debugging. While explaining what each line is supposed to do, you’ll often hear yourself say something the code doesn’t actually do. And if you ask for help, include the full error message: it’s the first thing anyone will ask for.
Exercise: fix this program
This program should calculate the average of four grades and print Average: 88.25. It has two bugs. One throws an exception; the other throws nothing but gives the wrong result.
int[] grades = { 90, 85, 78, 100 };
int sum = 0;
for (int i = 0; i <= grades.Length; i++)
{
sum += grades[i];
}
double average = sum / grades.Length;
Console.WriteLine($"Average: {average}");
Run it, read the error, fix it, and then use the debugger to find the second bug.
Suggested solution
When you run it, you get this:
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in .../Program.cs:line 6
Line 6 is sum += grades[i];. The array has four grades, at positions 0 to 3, but with <= the for loop goes up to i = 4. Change <= to <. Now it runs, but prints:
Average: 88
There’s no exception, so the message can’t help you. Set a breakpoint on the double average line and press F5. In VARIABLES you see that sum is 353, which is right. In WATCH, add sum / grades.Length and you’ll see 88. It’s the integer division from chapter 2: sum and grades.Length are both int, so C# drops the decimals before storing the result in the double. The fix is to make sum a double:
int[] grades = { 90, 85, 78, 100 };
double sum = 0;
for (int i = 0; i < grades.Length; i++)
{
sum += grades[i];
}
double average = sum / grades.Length;
Console.WriteLine($"Average: {average}");
Average: 88.25
If your computer uses a comma for decimals, you’ll see 88,25.
What you learned
- A compiler error keeps the program from running; an exception stops it while it runs.
- The first line of an exception has the type and the message. The stack trace tells you which line of your file it happened on and who called it.
FormatException,IndexOutOfRangeException,KeyNotFoundExceptionandNullReferenceException, and what each one means.try/catchcatches one type of exception and lets the program continue.- For user input,
TryParsebeats catching the exception. - In VS Code: F9 sets a breakpoint, F5 starts, F10 steps one line, F11 steps into a method, and VARIABLES and WATCH show you the values.
That wraps up Part 1. You can now store data, make decisions, repeat, organize with collections and methods, and fix what breaks. In Part 2 we start object-oriented programming: how to create your own types to represent the things in your program.
Stuck on an error?
Send me a DM on Instagram or ask in the Discord community. Paste the full error message and your code, and we’ll read it together.
