Exception Handling
Exceptions separate normal program logic from error-handling logic. A function can throw an exception, and a caller can handle it inside a catch block.
Throwing and Catching an Exception
Safe division
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double numerator, double denominator)
{
if (denominator == 0)
throw invalid_argument("Denominator cannot be zero.");
return numerator / denominator;
}
int main()
{
try
{
cout << divide(10, 0) << endl;
}
catch (const exception& error)
{
cout << "Error: " << error.what() << endl;
}
return 0;
}Exception Flow
- Code runs normally inside
try. - A problem causes an exception to be thrown.
- Control moves to a matching
catchblock. - The program can report the problem or recover safely.
Use exceptions thoughtfully
Exceptions are appropriate for exceptional failures, not as a replacement for ordinary conditions such as a normal menu choice.
Practice task
Write a function that throws out_of_range when a mark is below 0 or above 100.
Lesson Summary
Respond to runtime problems using try, throw, catch, and standard exceptions.