C++如果catch块内部发生异常会发生什么

  • 本文关键字:异常 如果 内部 C++ catch c++
  • 更新时间 :
  • 英文 :


如果catch块内部发生异常,会发生什么?

try {}
catch(...)
{
stream.close(); // IO exception here
}

默认行为是什么?

不会有什么特别的事情发生。新的异常对象将由调用内的throw表达式初始化,并开始搜索匹配的catch处理程序,在转义函数调用时,将在最近的封闭try块(封闭所示的try/catch对(上继续搜索。旧的异常对象将在离开旧处理程序时在堆栈展开过程中被销毁,因为它没有被重新抛出。

如果在catch块中遇到异常,则会抛出该异常。

如果不想抛出异常,可以为该异常再添加一个catch块。

try {
}catch(...){
try{
stream.close(); // IO exception here
}catch(IOException ioException){
}
}

据我记忆所及:

#include <cstdio>
#include <fstream>
#include <stdexcept>
static auto foo(char const* path) try {
if (not path) 
throw std::runtime_error("path was nullptr");
else
std::printf("Opening file '%s'n", path);
auto f = std::ifstream(path);
if (not f)
throw std::runtime_error("Failed to open file in foo(char const*)");

char x[5] {};
f.read(x, 4); // 4 chars + ''
std::printf("File type: %sn", x + 1);

return x[1]; // 'E' on linux
} catch (std::runtime_error const& e) {
// If an exception occurs here, unless the call to foo(char const*)
// was itself in a try-catch, the exception will be uncaught and std::terminate will be called
// Whether std::terminate causes any stack unwinding to occur is implementation defined.
// (That's not great.)
// If the function was marked `noexcept (true)` then std::terminate would get immediately called.

// f is destructed at the end of the scope (before the catch). 
// This is called "RAII": https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
std::fprintf(stderr, "%s: An exception occured:nt'%s'n", __func__, e.what());
throw; // rethrows the caught exception
}
int main(int, char** argv) {
std::printf("%c", foo(argv[0]));
}

实例

在函数try-catch块中:当文件对象超出范围时,它将被销毁;不管异常状态如何。

最新更新