当抛出异常时,尝试用cout语句阻塞行为

Try block behavior with cout statements when an exception is thrown

本文关键字:语句 cout 抛出异常      更新时间:2023-10-16

如果在try块中抛出异常之前包含cout语句,这些语句会被打印到控制台,还是会表现得好像try块从未执行过?例如:

void foo()
{
  try
  {
    cout << "1" << endl;
    cout << "2" << endl;
    bar();               //exception thrown in this function, but caught below
  }
  catch (exception e)
  {
    cout << e.what();    //assume the message is "error"
  }
}

这个函数的输出是否为

1
2
error

error

输出为

1
2
error

异常不会"撤消"

的效果
cout << "1" << endl;
cout << "2" << endl;