Chapter 16: Exception Handling

1. What is an Exception? (Super Simple Analogy)

An exception is like an emergency alarm that goes off when something unexpected happens:

  • You try to divide by zero → “Hey! You can’t do that!”
  • You try to open a file that doesn’t exist → “File not found!”
  • You try to parse “abc” as a number → “That’s not a number!”

Instead of crashing, the program throws an exception (like raising a red flag), and you can catch it and decide what to do.

2. The try-catch-finally Block – The Core of Exception Handling

Syntax:

C#

Real example – Dividing two numbers safely

C#

Output examples:

  • User enters “10” and “2” → “Result: 10 / 2 = 5”
  • User enters “abc” → “Error: Please enter valid numbers!”
  • User enters “10” and “0” → “Error: Cannot divide by zero!”
  • In all cases → “Thank you for using the calculator!” (finally runs)

3. Throwing Exceptions Yourself (When You Want to Signal an Error)

You can throw exceptions manually using the throw keyword.

C#

4. Creating Custom Exceptions (Professional & Meaningful)

Sometimes built-in exceptions like ArgumentException are not specific enough. You should create your own exception classes for your domain.

Best practice:

  • Inherit from Exception (or more specific like ApplicationException)
  • Add custom properties if needed
  • Provide good messages and constructors
C#

Output:

text

5. Best Practices for Exception Handling (2026 Style)

  1. Catch specific exceptions first, then general Exception last
  2. Never catch Exception unless you really need to (and log it!)
  3. Don’t swallow exceptions (never do catch { } empty)
  4. Use finally for cleanup (closing files, connections, etc.)
  5. Throw exceptions early (fail fast)
  6. Create custom exceptions for your business domain
  7. Log exceptions (use ILogger in real apps)

Mini-Project: Safe File Reader with Exception Handling

C#

Summary – What We Learned Today

  • try-catch-finally → catch and handle errors gracefully
  • Multiple catch blocks → handle specific exceptions first
  • throw → manually signal an error
  • Custom exceptions → make errors meaningful for your domain
  • finally → always runs (cleanup)
  • Best practice → catch specific → general → log → don’t swallow

Your Homework (Super Practical!)

  1. Create a new console project called ExceptionMaster
  2. Create a class SafeCalculator with methods:
    • Divide(int a, int b) → throw DivideByZeroException if b == 0
    • ParseNumber(string input) → throw custom InvalidNumberFormatException if not a number
  3. Create your own custom exception: InvalidNumberFormatException
  4. In Program.cs: Ask user for two numbers and operation (+, -, *, /), use try-catch to handle all possible errors nicely

Next lesson: Generics – we’re going to learn how to write super reusable, type-safe code that works with any data type!

You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with custom exceptions or finally blocks? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *