Exceptions
Exception Flow
An exception skips the rest of the try block and resumes in the matching handler.
Exception Flow
exception_flow.cpp
#include <iostream>
#include <stdexcept>
int runSteps(int steps) {
std::cout << "start" << std::endl;
if (steps == 0) {
throw std::runtime_error("no steps");
}
for (int step = 1; step <= steps; step++) {
std::cout << "step=" << step << std::endl;
}
return steps;
}
int main() {
int steps = ;
try {
int completed = runSteps(steps);
std::cout << "completed=" << completed << std::endl;
} catch (const std::runtime_error& error) {
std::cout << "completed=0" << std::endl;
}
std::cout << "afterCatch=1" << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
int runSteps(int steps) {
std::cout << "start" << std::endl;
if (steps == 0) {
throw std::runtime_error("no steps");
}
for (int step = 1; step <= steps; step++) {
std::cout << "step=" << step << std::endl;
}
return steps;
}
int main() {
int steps = ;
try {
int completed = runSteps(steps);
std::cout << "completed=" << completed << std::endl;
} catch (const std::runtime_error& error) {
std::cout << "completed=0" << std::endl;
}
std::cout << "afterCatch=1" << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
int runSteps(int steps) {
std::cout << "start" << std::endl;
if (steps == 0) {
throw std::runtime_error("no steps");
}
for (int step = 1; step <= steps; step++) {
std::cout << "step=" << step << std::endl;
}
return steps;
}
int main() {
int steps = ;
try {
int completed = runSteps(steps);
std::cout << "completed=" << completed << std::endl;
} catch (const std::runtime_error& error) {
std::cout << "completed=0" << std::endl;
}
std::cout << "afterCatch=1" << std::endl;
return 0;
}
exception flow
When a function throws, the caller's `try` block stops at that call and control moves to `catch`.