C++ Exceptions

throw, try and catch.

✍️ 2 exercises in this lesson
  • throw std::runtime_error("message"); signals an error.
  • try { } catch (const std::exception& e) { } handles it; e.what() returns the message.
  • Standard exceptions live in <stdexcept>: invalid_argument, out_of_range, runtime_error...
  • catch (...) catches anything.

Key Takeaways: C++ Exceptions

Mastering C++ Exceptions helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Exceptions Code Example

C++
#include <iostream>
#include <stdexcept>
#include <vector>

double divide(double a, double b) {
    if (b == 0) throw std::invalid_argument("division by zero");
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 4) << "\n";
        std::cout << divide(1, 0) << "\n";
    } catch (const std::invalid_argument& e) {
        std::cout << "Error: " << e.what() << "\n";
    }

    std::vector<int> v = {1, 2, 3};
    try {
        std::cout << v.at(10) << "\n";
    } catch (const std::out_of_range&) {
        std::cout << "Index out of range\n";
    }
    return 0;
}
Output
2.5
Error: division by zero
Index out of range
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Exceptions Practice Exercises

Check what you learned in “C++ Exceptions”.

/ 2 solved
Fill in the blank

Signal an invalid argument.

 std::invalid_argument("bad value");
✓ Correct! Not quite. Try again.
Multiple choice

Which method returns an exception's message?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services