AnyCompiler

Exceptions and Resource Cleanup

A try block runs code that might throw; a matching catch block handles it if it does. Separately, any object implementing IDisposable can be wrapped in a using block — when that block ends, Dispose() is guaranteed to run, even if an exception is thrown partway through.

using System;

class Resource : IDisposable {
    public void Dispose() {
        Console.WriteLine("Resource cleaned up");
    }
}

class Program {
    static void Main() {
        try {
            using (var r = new Resource()) {
                Console.WriteLine("Using resource");
                throw new InvalidOperationException("something went wrong");
            }
        } catch (InvalidOperationException e) {
            Console.WriteLine("Caught: " + e.Message);
        }
    }
}
Output
Using resource
Resource cleaned up
Caught: something went wrong

Resource cleaned up prints before Caught: — Dispose() runs as the exception unwinds out of the using block, before the catch further up ever gets a chance to run. This is C#'s answer to C++'s RAII and Java's try-with-resources: deterministic cleanup, guaranteed by the language even when something goes wrong.

That's the foundation of C#: classes and interfaces for structuring code, properties for controlled access without getter/setter boilerplate, structs for genuine value-type semantics alongside reference types, generics and LINQ for reusable, type-safe collection code, and delegates, events, and using/IDisposable for C#'s own take on callbacks and deterministic cleanup. From here, the best next step is practice — pick a small program and build it, leaning on the compiler's static type checking to catch mistakes as you go.

Practice exercise

Write a method SafeDivide(int a, int b) that returns a / b, but catches DivideByZeroException and returns 0 if b is 0. Call it with (10, 0) and print the result.

← Nullable Types and Null SafetyMore lessons coming soon