C# Basics

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

C#
Run code →
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");
    }
}
Result of running the code
84

Practice 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.

All challenges