Ch 12 · Exception Handling · C++
Topic 12 of 13 in C++ — Complete Tutorial (Beginner) — 2 lessons.
try / catch / throw
Programs face unpredictable problems at runtime — invalid input, division by zero, missing data. C++ handles these with exceptions. Risky code goes in a try block; if something goes wrong you throw an exception, and a matching catch block handles it gracefully instead of crashing. You can throw standard exceptions or simple values, and catch them by type.
Validating with Exceptions
Throwing exceptions is the clean way to validate input: when a function receives data that breaks its rules, it throws immediately rather than continuing with bad data. The caller wraps the call in try/catch and responds. A descriptive message — naming the rule and the bad value — makes debugging easy.