computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🧯

🎓

⏱ 25 min

Free

Exceptions & Debugging

Handle errors with try/catch, use TryParse for safe input and debug with breakpoints.

🎯 What you will learn

  • Catch exceptions with try/catch/finally
  • Parse input safely with int.TryParse
  • Debug with breakpoints in VS Code

👋 Let’s get started!

Players will do unexpected things — guaranteed 😅. Robust code expects problems. Let’s handle errors and learn the debugger, a pro’s best friend.

🪜 Step by step

1. 🧯 try / catch

Catch specific exceptions.

try
{
    int[] arr = { 1, 2, 3 };
    Console.WriteLine(arr[5]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("No item there!");
}
2. ✅ TryParse

Safely convert text to numbers without exceptions.

if (int.TryParse("42", out int n))
    Console.WriteLine(n + 1);
else
    Console.WriteLine("Not a number");
3. 🐞 Breakpoints

In VS Code, click left of a line number to set a red dot, then press F5. The program pauses there so you can inspect every variable.

🧪 Try it!

Read the code, guess what it prints, then press 👀 Show output.

Safe menu input

string[] typed = { "2", "banana", "9" };
foreach (var t in typed)
{
    if (!int.TryParse(t, out int choice))
    {
        Console.WriteLine($"\"{t}\" isn't a number 🙅");
        continue;
    }
    try
    {
        if (choice < 1 || choice > 3) throw new ArgumentOutOfRangeException(nameof(choice));
        Console.WriteLine($"You picked option {choice} ✅");
    }
    catch (ArgumentOutOfRangeException)
    {
        Console.WriteLine($"{choice} isn't on the menu");
    }
}

TryParse pattern

string text = "12";
if (int.TryParse(text, out int age))
{
    Console.WriteLine($"Age: {age}");
}

📖 Key words

Tap a card to flip it over!

Exception
An error you can catch 🧯
TryParse
Converts text safely ✅
Breakpoint
Pauses the program for inspection 🔴
Stack trace
The trail of where an error happened 👣

🏆 Challenge

Predict the output.

Challenge

try
{
    Console.WriteLine("Start");
    int x = int.Parse("oops");
    Console.WriteLine("Never printed");
}
catch (FormatException)
{
    Console.WriteLine("Bad format");
}
finally
{
    Console.WriteLine("Done");
}

Knowledge Check Quiz

  1. Why use int.TryParse instead of int.Parse?
  2. When does finally run?
  3. What’s a breakpoint for?
← Previous lesson
Next lesson →