⚠️ 原样重抛,类型一点没变
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)中间那层接住之后又原样扔了出去:
#include <iostream>
#include <stdexcept>
#include <string>
static std::string path;
static void mark(const char *n) { if (!path.empty()) path += ">"; path += n; }
/* 中间这层管不了,就原样往上抛 —— 但顺手留个记号 */
static int middle(int v) {
mark("middle");
try {
if (v < 0) throw std::invalid_argument("neg");
return v;
} catch (const std::exception &) {
mark("caught");
throw; /* 原样重抛,类型和内容都不变 */
}
}
int main() {
int ok = middle(5);
int top_caught = 0;
std::string msg;
try {
middle(-1);
} catch (const std::invalid_argument &e) {
top_caught = 1;
msg = e.what();
}
std::cout << ok << "/" << top_caught << "/" << msg << "/" << path << "\n";
return 0;
}
全部评论