C++ Language & Safety
Exceptions & try/catch
Throw signals an error; catch handles it; uncaught = abort.
Concept core idea Watch out easy to get wrong
Concept
Key concepts
throwraises an exception; a matchingcatchhandles it..at()throwsstd::out_of_rangeon a bad index.- An uncaught exception propagates to
std::terminate→ 'Aborted (core dumped)'. That crash means nobody handled it. - Wrap risky code in
try { ... } catch (const std::exception& e) { ... };e.what()gives the message. - Catch by
constreference (avoids slicing and copies).
Handle vs abort
try { a.at(10) = 4; } // throws
catch (const std::out_of_range& e){
std::cout << e.what(); // handled — program continues
} Watch out
Easily confused
uncaught throw vs bug in .at()
The abort is from nobody catching the exception —
.at() did its job by detecting the bad index.catch by value vs by reference
Catch by
const& — catching by value can slice the exception object and copies it.Test yourself
6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.