Chapter 16: Exception Handling

Exception Handling in C++: Making Your Code Robust & Reliable

Hello my wonderful student! 🌟 Welcome to Lesson 16 β€” Exception Handling β€” one of the most important topics for writing production-quality C++ code!

Exceptions are C++’s way of saying: β€œSomething went wrong (file not found, division by zero, out of memory, invalid input…), and I’m going to throw the problem up the call stack until someone catches it and handles it properly.”

Think of exceptions like a fire alarm:

  • When a problem occurs β†’ the alarm goes off (throw)
  • Someone (the nearest handler) hears it and takes action (catch)
  • If no one handles it β†’ the program terminates (like calling emergency services)

Today we’ll cover everything in great detail:

  • try, catch, throw
  • Multiple catch blocks & catch-all
  • Custom exceptions (your own error classes)
  • noexcept specifier (modern C++ safety & performance)

Let’s go step-by-step with real-life analogies and complete examples!

1. Basic try-catch-throw – The Core Mechanism

Syntax:

C++

Important rules:

  • Code inside try is normal code
  • When an exception is thrown β†’ execution jumps to the matching catch
  • If no catch matches β†’ program calls std::terminate() (crashes)

Simple example – Division by zero

C++

Output:

text
What happened?
  • divide(10, 0) β†’ throws std::runtime_error
  • Control jumps to catch block β†’ prints error message
  • Program does NOT crash β€” it continues normally

2. Catching Multiple Exception Types

C++

Best practice:

  • Catch specific exceptions first
  • Catch base classes (like std::exception) last if needed
  • Use catch by reference (&) β†’ avoids copying

3. Custom Exceptions – Your Own Error Types

You can (and should!) create your own exception classes β€” it makes error handling much clearer.

Example – Custom exception hierarchy

C++

Output (for negative amount):

text

Why custom exceptions?

  • Clearer error messages
  • Specific handling for different problems
  • Easy to catch groups of related errors

4. noexcept Specifier – Modern C++ Safety & Performance

noexcept tells the compiler: β€œThis function promises never to throw an exception. If it does β†’ call std::terminate() immediately.”

Why use it?

  • Performance (compiler can optimize better)
  • Safety (document that exceptions are not expected)
  • Move semantics (required for some STL containers)

Examples:

C++

Best practice (2025+):

  • Mark destructors, move constructors, move assignment operators as noexcept
  • Use noexcept on small, performance-critical functions that really don’t throw

5. Full Practical Example – File Reading with Exception Handling

C++

Tip: Always catch std::exception& as a fallback β€” it catches most standard exceptions.

Your Mini Homework (Try These!)

  1. Write a function safeDivide(double a, double b) that throws a custom DivisionByZeroException if b == 0.
  2. Create a SafeArray class that throws IndexOutOfRangeException when accessing invalid indices.
  3. Write a function marked noexcept that allocates memory β€” explain what happens if new throws.

You’re doing absolutely incredible! Exception handling is what separates toy programs from real, reliable software β€” you’ve just mastered one of the most critical topics!

Next lesson: File I/O & Streams β€” reading/writing files, binary data, serialization β€” super useful for real apps!

Any questions? Confused about custom exceptions or noexcept? Want more examples with stack unwinding or multiple catch blocks? Just ask β€” your friendly C++ teacher is right here for you! πŸš€

You may also like...

Leave a Reply

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