Learn C# ยท 8/15

Error Handling and Debugging

8 min read

Welcome back, developer! ๐Ÿš€

So far, youโ€™ve been writing code that (hopefully) follows the "Happy Path"โ€”that magical scenario where users always enter the right data, files always exist, and the internet connection never drops.

But letโ€™s be real: The Happy Path is a lie. ๐Ÿคฅ

In the real world, users type "banana" into age fields, servers catch fire, and files go missing. If your application crashes the moment something unexpected happens, users will delete it faster than you can say "Stack Overflow."

In this module, we are going to learn how to anticipate disaster, handle it with style, and fix it when things go boom.


1. Exceptions: What They Are and Why They Happen ๐Ÿ’ฅ

The Definition

In C#, an Exception is an object that encapsulates information about an unusual or error condition that occurs during the execution of a program. When this condition occurs, the runtime "throws" this object up the call stack.

The Problem

Imagine you are building a calculator. You write a line that divides numberA by numberB.
If a user sets numberB to 0, the CPU literally cannot compute that. It panics. Without error handling, your entire application terminates immediately (crashes) and the user sees a scary error message (or just a desktop).

Real-Life Simulation

Think of a vending machine.

  • Happy Path: You put in a dollar, press "Soda", and get a soda.
  • Exception: You put in a dollar, press "Soda", but the soda is stuck.
  • Unhandled Exception: The machine explodes.
  • Handled Exception: The machine beeps, says "Error: Item Stuck," and returns your dollar.

Common C# Exceptions

You will see these a lot in your career. Get to know them:

  1. NullReferenceException: The Billion Dollar Mistake. You tried to use a variable that points to... nothing (null).
  2. IndexOutOfRangeException: You tried to access index 5 in a list that only has 3 items.
  3. DivideByZeroException: Math rules still apply in code.
  4. FileNotFoundException: You asked for secret_plans.txt, but it's not on the hard drive.

Example: The Crash

csharp
int numerator = 10;
int denominator = 0;

// This line causes the program to crash immediately.
// No code after this will execute.
int result = numerator / denominator; 

Console.WriteLine("This will never print.");

Fun Fact: The term "Bug" became popular in 1947 when Grace Hopper's team found an actual moth trapped in a relay of the Harvard Mark II computer. They taped it into the logbook with the note: "First actual case of bug being found." ๐Ÿฆ‹


2. Try-Catch-Finally: Gracefully Handling Errors ๐Ÿ›ก๏ธ

The Solution

To stop the crash, we need a safety net. In C#, this is the try-catch block.

  • try: "Attempt to run this risky code."
  • catch: "If the risky code explodes, jump here and do this instead of crashing."
  • finally: "No matter what happens (error or success), run this code before leaving."

Syntax and Implementation

csharp
string input = "0";

try
{
    // 1. The Risky Zone
    int divisor = int.Parse(input);
    int result = 100 / divisor;
    Console.WriteLine($"Result is {result}");
}
catch (DivideByZeroException ex)
{
    // 2. Specific Handling
    // This runs ONLY if a DivideByZeroException occurs
    Console.WriteLine("Whoops! You cannot divide by zero.");
}
catch (FormatException ex)
{
    // 3. Handling bad inputs (like "banana")
    Console.WriteLine("Please enter a valid number.");
}
catch (Exception ex)
{
    // 4. The Catch-All (General Handling)
    // Best practice: Log the specific error message here.
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally
{
    // 5. Cleanup
    // This runs ALWAYS. Even if there was an error.
    Console.WriteLine("Calculation attempt finished.");
}

Industry Best Practices ๐Ÿ—๏ธ

  1. Specific before General: Always catch specific exceptions (like DivideByZeroException) before the generic Exception. C# checks catch blocks from top to bottom.
  2. Don't Swallow Errors: A "swallowed" error is an empty catch block.
    csharp
    catch (Exception) { } // NEVER DO THIS.
    This hides the problem. You won't know why your app is behaving weirdly because you silenced the alarm.
  3. The finally block: This is critical for releasing resources. If you open a file or a database connection, put the close/dispose command in finally so it closes even if the app errors out.

3. Throwing Custom Exceptions ๐Ÿˆ

The Problem

Sometimes C# doesn't know that something is an error in your specific business.
If you are writing a Banking App, withdrawing money when the balance is 0 is valid math (0 - 100 = -100), but it is a Business Rule Violation.

The Solution

You can create your own exceptions and throw them manually.

Creating a Custom Exception

Standard practice is to create a class that inherits from Exception and ends the name with Exception.

csharp
// Define the custom exception
public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message)
    {
    }
}

Throwing the Exception

Use the throw keyword to stop execution and signal an error.

csharp
public class BankAccount
{
    public decimal Balance { get; private set; } = 50;

    public void Withdraw(decimal amount)
    {
        if (amount > Balance)
        {
            // Stop everything! Throw our custom error.
            throw new InsufficientFundsException($"You need ${amount} but only have ${Balance}.");
        }

        Balance -= amount;
        Console.WriteLine($"Remaining Balance: {Balance}");
    }
}

// Usage
try 
{
    var myAccount = new BankAccount();
    myAccount.Withdraw(1000); // This triggers the throw
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine(ex.Message); // Prints: You need $1000 but only have $50.
}

๐Ÿšจ CRITICAL INDUSTRY WARNING: Rethrowing

When you catch an exception and want to pass it up the chain, use throw;, NOT throw ex;.

  • throw; -> Preserves the original stack trace (shows you exactly line number where the error started).
  • throw ex; -> Resets the stack trace. It looks like the error started inside the catch block. This makes debugging a nightmare.
csharp
catch (Exception ex)
{
    // Do some logging
    Log(ex);
    
    throw; // โœ… GOOD: Preserves history
    // throw ex; // โŒ BAD: Erases history
}

4. Debugging Basics: Breakpoints and Stepping ๐Ÿ•ต๏ธโ€โ™‚๏ธ

The Problem

Your code isn't crashing, but it's giving the wrong answer. You stare at the code for hours. You add 50 Console.WriteLine("Here 1"), Console.WriteLine("Here 2") statements.
Stop. There is a better way.

The Solution: The Interactive Debugger

Modern IDEs (Visual Studio, VS Code, Rider) have powerful debuggers that let you freeze time and inspect your code while it runs.

The Toolkit

1. Breakpoints (F9) ๐Ÿ›‘

A breakpoint is a stop sign. Click in the left margin next to a line of code (a red dot will appear). When your program reaches that line, it pauses.

2. The Watch Window ๐Ÿ”ญ

While paused, hover your mouse over any variable. The IDE will show you its current value. You can also add variables to a "Watch" window to track how they change as you move through the code.

3. Stepping Controls

Once paused, you control the flow:

  • Step Over (F10): Run the current line and go to the next one. If the line is a function call, run the whole function instantly and stop at the next line in the current file.
    • Use when: You trust the function you are calling and just want to move to the next step.
  • Step Into (F11): If the line is a function call, go inside that function and pause at the first line there.
    • Use when: You suspect the bug is inside that specific function.
  • Step Out (Shift + F11): Run the rest of the current function and pause immediately after it returns.
    • Use when: You accidentally stepped into a long boring function and want to get back out.

Hands-On Simulation

Imagine this code logic is flawed:

csharp
int total = 0;
for (int i = 0; i < 5; i++)
{
    total = total + i; // Set Breakpoint Here (F9)
}
  1. Press F5 (Start Debugging).
  2. Execution stops at the breakpoint.
  3. Hover over i. It says 0. Hover over total. It says 0.
  4. Press F10 (Step Over). The loop runs again.
  5. Hover over i. It says 1.
  6. You can watch the logic unfold step-by-step.

Imagination Time: Debugging is like being a detective in a movie where you can freeze time, walk around the crime scene, check everyone's pockets, and then unfreeze time for one second to see what happens next.


Summary

  • Exceptions are object representations of errors.
  • Try-Catch-Finally is your shield against crashes.
  • Throw lets you enforce your own rules.
  • Debuggers are better than Console.WriteLine for finding logic errors.
  • Don't swallow exceptions. It's like taking the batteries out of a smoke detector.

Now, go forth and write code that fails gracefully! ๐Ÿง˜โ€โ™‚๏ธ


๐Ÿ“š References & Further Reading

Challenge

Challenge: Implement a Robust Bank Transaction Processor

You are tasked with improving a simple banking application by adding robust error handling. Your goal is to implement the ProcessTransactions method and a custom exception class to handle various failure scenarios gracefully.

Requirements:

  1. Custom Exception: Complete the InsufficientFundsException class. It must inherit from System.Exception and include a constructor that accepts a string message and passes it to the base class constructor.

  2. Transaction Processing Logic: Implement the ProcessTransactions method. It must iterate through a list of transactions.

    • Wrap the entire foreach loop in a try...finally block.
  3. Handle Invalid Data: Inside the loop, for each transaction, use a nested try...catch block to handle the parsing of the Amount string into a decimal. If a FormatException occurs, the program should not crash; it should simply skip that single transaction and continue to the next one.

  4. Enforce Business Rules: After successfully parsing the amount, process the transaction:

    • If the transaction Type is "deposit", add the amount to the balance.
    • If the Type is "withdrawal", first check if the Balance is sufficient. If the withdrawal amount is greater than the current balance, you must throw a new instance of your InsufficientFundsException. This action should halt all further transaction processing.
  5. Resource Cleanup: The finally block of the outer try statement must contain a comment: // Simulate closing transaction log. This block should always execute, regardless of whether the processing completes successfully or an exception is thrown.

Expected result

Your final code should correctly implement the InsufficientFundsException and the ProcessTransactions method according to the requirements.

  1. The InsufficientFundsException class must inherit from System.Exception and have a public constructor public InsufficientFundsException(string message) : base(message) {}.

  2. The ProcessTransactions method must contain a try...finally block wrapping a foreach loop that iterates over the transactions.

  3. Inside the foreach loop, there must be a try...catch (FormatException) block. The code to parse the Amount string must be inside this try block. The catch block should contain a continue; statement to skip the invalid transaction.

  4. The logic must correctly identify "withdrawal" transactions and check if Balance >= parsedAmount. If the check fails, it must execute throw new InsufficientFundsException("...");.

  5. For valid transactions, the Balance property should be correctly updated (+= for deposit, -= for withdrawal).

  6. The finally block must be present at the end of the ProcessTransactions method and contain the specified comment // Simulate closing transaction log.

csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.