繁体   English   中英

C++ 如果在catch 块内发生异常怎么办?

[英]C++ what happens if an exception occurs inside catch block?

如果在 catch 块内发生异常会怎样?

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

默认行为是什么?

没有什么特别的事情会发生。 一个新的异常 object 将由调用中的throw表达式初始化,并且将开始搜索匹配的catch处理程序,在 escaping 上,function 调用将在最近的封闭try块(封闭显示的try / catch对)上继续。 旧异常 object 将在离开旧处理程序时在堆栈展开期间被销毁,因为它没有被重新抛出。

如果您在 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 + '\0'
  std::printf("File type: %s\n", 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:\n\t'%s'\n", __func__, e.what());
  throw; // rethrows the caught exception
}

int main(int, char** argv) {
  std::printf("%c", foo(argv[0]));
}

实例

在 function try-catch块中:文件 object 在离开 scope 时被销毁; 不管异常state。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM