Exception Handling in C#

When Kashvee tries to start a car that doesn't exist, don't crash the whole app.

60-Second Version: Exceptions = runtime errors. try = "attempt this". catch = "if it fails, do this instead". finally = "always do this".

1. The Problem: App Crashes

Without handling, one bad line kills everything.

Dictionary<string, Car> garage = new Dictionary<string, Car>();
garage["Kunal"] = new Car { Owner = "Kunal" };

Car car = garage["Kashvee"]; // KeyNotFoundException. App dies here.
Console.WriteLine("This never runs");

2. The Fix: try-catch

Wrap risky code. Catch the problem and recover.

try
{
    Car car = garage["Kashvee"]; // Risky: Key might not exist
    car.Start();
}
catch (KeyNotFoundException ex)
{
    Console.WriteLine("Kashvee has no car in garage yet.");
    Console.WriteLine($"Error: {ex.Message}");
}

Console.WriteLine("App keeps running"); // This now runs

3. finally: Always Runs

Use for cleanup. Runs if try succeeds or fails.

Car rental = null;
try
{
    rental = RentCar("Kiaan");
    rental.Start();
}
catch (Exception ex)
{
    Console.WriteLine("Could not rent car");
}
finally
{
    if(rental!= null) rental.Return(); // Always return car to lot
}
Beginner Trap: Empty catch { } hides bugs. Always log or handle the error. Silent failures are the worst bugs to debug.

Quick Check ๐Ÿง 

Next: File I/O - Save Kashvee's car list to disk and load it later. Real apps need persistence.

Comments on Exception Handling (0)

No comments yet. Be the first to share your thoughts!