AnyCompiler

Exceptions aur Resource Cleanup

Ek try block wo code run karta hai jo throw kar sakta hai; agar wo throw kare to matching catch block use handle karta hai. Alag se, IDisposable implement karne wale kisi bhi object ko using block mein wrap kiya ja sakta hai — jab wo block khatam hota hai, Dispose() ka run hona guaranteed hai, chahe beech mein koi exception throw bhi ho jaaye.

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, Caught: se pehle print hota hai — jab exception using block se unwind hoti hai tab Dispose() run hota hai, usse pehle hi ki upar wala catch chance paaye run hone ka. Ye C++ ke RAII aur Java ke try-with-resources ka C# wala jawab hai: deterministic cleanup, jo language khud guarantee karti hai chahe kuch bhi galat ho jaaye.

Ye hai C# ki foundation: code structure karne ke liye classes aur interfaces, getter/setter boilerplate ke bina controlled access ke liye properties, reference types ke saath genuine value-type semantics ke liye structs, reusable aur type-safe collection code ke liye generics aur LINQ, aur callbacks aur deterministic cleanup ke liye C# ka apna take — delegates, events, aur using/IDisposable. Yahan se, best next step practice hai — ek chhota program choose karo aur use banao, compiler ki static type checking par rely karte hue mistakes pakadne ke liye.

Practice exercise

Ek method SafeDivide(int a, int b) likho jo a / b return kare, lekin DivideByZeroException catch kare aur 0 return kare agar b 0 ho. Ise (10, 0) se call karo aur result print karo.

← Nullable Types aur Null SafetyAur lessons jald aa rahe hain