C++ Tutorial · Advanced C++ · Lesson 18 of 21
C++ Exceptions
throw, try, catch, standard exception types and noexcept.
Exceptions
Throw an exception to signal an error the caller must handle; catch by const reference:
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
int parsePort(const std::string& s) {
long long n = std::stoll(s); // throws invalid_argument / out_of_range
if (n < 1 || n > 65535) throw std::out_of_range("port must be 1-65535");
return static_cast<int>(n);
}
std::optional<std::string> findUser(int id) {
if (id == 1) return "Ada";
return std::nullopt;
}
int main() {
for (const auto& input : {"42", "abc", "99999999999"}) {
try {
int port = parsePort(input); // may throw before anything is printed
std::cout << "parsed " << port << '\n';
} catch (const std::invalid_argument& e) {
std::cout << "invalid: " << e.what() << '\n';
} catch (const std::out_of_range& e) {
std::cout << "out of range: " << e.what() << '\n';
}
}
auto maybe = findUser(2);
std::cout << maybe.value_or("no user") << '\n';
}
Output
parsed 42 invalid: stoll out of range: port must be 1-65535 no user
Run this on your computer — see “Get Started” for setup.
Standard types in <stdexcept>: std::invalid_argument, std::out_of_range, std::runtime_error. Thanks to RAII, resources are released while the exception propagates. Mark functions that never throw as noexcept.
Many codebases also use std::optional<T> or C++23's std::expected<T, E> for expected failures.
Test yourself
How should you catch exceptions in C++?
By valueBy pointerBy const referenceWith catch(...) only
Show answer
Answer: By const reference