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:
NullReferenceException: The Billion Dollar Mistake. You tried to use a variable that points to... nothing (null).IndexOutOfRangeException: You tried to access index 5 in a list that only has 3 items.DivideByZeroException: Math rules still apply in code.FileNotFoundException: You asked forsecret_plans.txt, but it's not on the hard drive.
Example: The Crash
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
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 ๐๏ธ
- Specific before General: Always catch specific exceptions (like
DivideByZeroException) before the genericException. C# checks catch blocks from top to bottom. - Don't Swallow Errors: A "swallowed" error is an empty catch block.This hides the problem. You won't know why your app is behaving weirdly because you silenced the alarm.csharp
catch (Exception) { } // NEVER DO THIS. - The
finallyblock: This is critical for releasing resources. If you open a file or a database connection, put the close/dispose command infinallyso 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.
// 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.
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 thecatchblock. This makes debugging a nightmare.
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:
int total = 0;
for (int i = 0; i < 5; i++)
{
total = total + i; // Set Breakpoint Here (F9)
}- Press F5 (Start Debugging).
- Execution stops at the breakpoint.
- Hover over
i. It says0. Hover overtotal. It says0. - Press F10 (Step Over). The loop runs again.
- Hover over
i. It says1. - 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.WriteLinefor 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:
Custom Exception: Complete the
InsufficientFundsExceptionclass. It must inherit fromSystem.Exceptionand include a constructor that accepts astringmessage and passes it to the base class constructor.Transaction Processing Logic: Implement the
ProcessTransactionsmethod. It must iterate through a list of transactions.- Wrap the entire
foreachloop in atry...finallyblock.
- Wrap the entire
Handle Invalid Data: Inside the loop, for each transaction, use a nested
try...catchblock to handle the parsing of theAmountstring into adecimal. If aFormatExceptionoccurs, the program should not crash; it should simply skip that single transaction and continue to the next one.Enforce Business Rules: After successfully parsing the amount, process the transaction:
- If the transaction
Typeis "deposit", add the amount to the balance. - If the
Typeis "withdrawal", first check if theBalanceis sufficient. If the withdrawal amount is greater than the current balance, you mustthrowa new instance of yourInsufficientFundsException. This action should halt all further transaction processing.
- If the transaction
Resource Cleanup: The
finallyblock of the outertrystatement 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.
The
InsufficientFundsExceptionclass must inherit fromSystem.Exceptionand have a public constructorpublic InsufficientFundsException(string message) : base(message) {}.The
ProcessTransactionsmethod must contain atry...finallyblock wrapping aforeachloop that iterates over the transactions.Inside the
foreachloop, there must be atry...catch (FormatException)block. The code to parse theAmountstring must be inside thistryblock. Thecatchblock should contain acontinue;statement to skip the invalid transaction.The logic must correctly identify "withdrawal" transactions and check if
Balance >= parsedAmount. If the check fails, it must executethrow new InsufficientFundsException("...");.For valid transactions, the
Balanceproperty should be correctly updated (+=for deposit,-=for withdrawal).The
finallyblock must be present at the end of theProcessTransactionsmethod and contain the specified comment// Simulate closing transaction log.