Exception Handling
Validate operations and recover from expected failures.
Introduction
Exceptions separate normal control flow from exceptional failure handling.
TryParse is preferred for expected invalid input. try/catch is appropriate when an API reports failure through exceptions.
Runnable C# example
Program.cs
using System;
class Program
{
static void Main()
{
string input = "42";
if (int.TryParse(input, out int value))
Console.WriteLine(value * 2);
else
Console.WriteLine("Invalid number");
}
}
84Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- First Invalid Age Validate typed ages and report where the first bad entry is instead of letting the program crash. Easy
- Sum the Valid Numbers Add up the entries that are whole numbers and skip everything else, the way try/except handles bad input. Easy