🔴 两个 catch,只进了具体那个
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)
#include <iostream>
#include <stdexcept>
#include <string>
/* 自定义异常要继承标准那一族,上层才好按类型分开接 */
class BadInput : public std::runtime_error {
public:
explicit BadInput(const std::string &what) : std::runtime_error(what) {}
};
static int parse(int v) {
if (v < 0) throw BadInput("negative");
return v * 2;
}
int main() {
int ok = parse(5);
int by_type = 0, by_base = 0;
std::string msg;
try {
parse(-1);
} catch (const BadInput &e) { /* 具体的写前面 */
by_type = 1;
msg = e.what();
} catch (const std::exception &) { /* 兜底的写后面 */
by_base = 1;
}
std::cout << ok << "/" << by_type << "/" << by_base << "/" << msg << "\n";
return 0;
}
全部评论