Systems CourseC/C++ · Linux · Memory
C++ Language & SafetyLesson 22 of 441 min read6 questions

Exceptions & try/catch

Throw signals an error; catch handles it; uncaught = abort.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. throw raises an exception; a matching catch handles it. .at() throws std::out_of_range on a bad index.
  2. An uncaught exception propagates to std::terminate → 'Aborted (core dumped)'. That crash means nobody handled it.
  3. Wrap risky code in try { ... } catch (const std::exception& e) { ... }; e.what() gives the message.
  4. Catch by const reference (avoids slicing and copies).

Handle vs abort

C++
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.