C# Basics

Exception Handling

Exceptions separate normal control flow from exceptional failure handling.

How it works

Validate operations and recover from expected failures.

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");
    }
}
Expected output
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.