Exceptions
Multiple Catches
Different exception types can be handled by different catch blocks.
Multiple Catches
multiple_catches.cpp
#include <iostream>
#include <stdexcept>
#include <string>
int loadScore(const std::string& mode) {
if (mode == "missing") {
throw std::invalid_argument("missing");
}
if (mode == "large") {
throw std::out_of_range("large");
}
return 88;
}
int main() {
std::string mode = ;
try {
int score = loadScore(mode);
std::cout << "score=" << score << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "problem=missing" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "problem=range" << std::endl;
}
std::cout << "mode=" << mode << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
#include <string>
int loadScore(const std::string& mode) {
if (mode == "missing") {
throw std::invalid_argument("missing");
}
if (mode == "large") {
throw std::out_of_range("large");
}
return 88;
}
int main() {
std::string mode = ;
try {
int score = loadScore(mode);
std::cout << "score=" << score << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "problem=missing" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "problem=range" << std::endl;
}
std::cout << "mode=" << mode << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
#include <string>
int loadScore(const std::string& mode) {
if (mode == "missing") {
throw std::invalid_argument("missing");
}
if (mode == "large") {
throw std::out_of_range("large");
}
return 88;
}
int main() {
std::string mode = ;
try {
int score = loadScore(mode);
std::cout << "score=" << score << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "problem=missing" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "problem=range" << std::endl;
}
std::cout << "mode=" << mode << std::endl;
return 0;
}
multiple catches
Catch blocks are tested in order, so specific exception types should appear before broader handlers.