gpt4 book ai didi

c++ - 异常处理,无法理解 :(

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:05:33 25 4
gpt4 key购买 nike

SO 的高级用户,

首先,我是 C++ 的新手,如果我没有明确提出问题,请原谅我。我看过一个异常处理的例子,但无法弄清楚这里发生了什么:(

http://codepaste.net/zqsrnj

enum ErrorCode {…}; // this is exception class
ErrorCode dispatcher() {
try {
throw; // what is thrown here in function?, if rethrow what is rethrown?
}
catch (std::bad_alloc&) {
return ErrorCode_OutOfMemory;
}
catch (std::logic_error&) {
return ErrorCode_LogicError;
}
catch (myownstdexcderivedclass&) {
return ErrorCode_42;
}
catch(...) { // this will handle the above throw in try block of dispatcher
return ErrorCode_UnknownWeWillAllDie;
}
}

ErrorCode apifunc() {
try {
// foo() might throw anything
foo();
}
catch(...) {
// dispatcher rethrows the exception and does fine-grained handling
return dispatcher();
}
return ErrorCode_Fine; //
}

ErrorCode apifunc2() {
try {
// bar() might throw anything
bar();
}
catch(...) {
return dispatcher();
}
return ErrorCode_Fine;
}

谁能逐行或整体解释这里发生的事情,控制是如何流动的?非常感谢任何帮助,非常感谢。

最佳答案

apifunc()apifunc2() 使用 dispatcher() 函数将异常转换为错误代码。

基本上,会发生如下情况:apifunc()(和类似的 apifunc2())尝试调用函数 foo()。如果foo()抛出异常,那么catch block 会调用dispatcher()获取异常对应的错误码,然后返回该错误代码。如果 foo() 没有抛出,apifunc() 返回 ErrorCode_Fine 表示没有错误。

dispatcher() 通过重新抛出最后抛出的异常来工作,即 foo() 抛出的异常。 dispatcher() 然后使用 catch block 检查抛出的异常,并返回正确的错误代码。例如,如果 foo() 抛出 std::bad_alloc,则该 catch block 将被执行并返回 ErrorCode_OutOfMemory;

为什么有人会这样做?

异常不一定在不同的编译(编译器、编译器标志等)之间二进制兼容,因此将异常转换为错误代码更易于跨模块边界移植。

关于c++ - 异常处理,无法理解 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com