[英]Why does this code produce different output from time to time?
Compiler:编译器:
➜ ~ /usr/bin/c++ --version
Apple clang version 11.0.0 (clang-1100.0.33.8)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Code:代码:
#include <iostream>
#include <exception>
#include <cstdlib>
void f() {
try {
throw std::runtime_error("Exception message.");
} catch(std::runtime_error& e) {
std::cout << e.what() << std::endl;
throw;
}
}
int main() {
using namespace std;
try {
f();
} catch(std::exception& e) {
cout << e.what() << endl;
terminate();
}
return EXIT_SUCCESS;
}
I found out that if i get rid of the "terminate()" in my catch it would work but i am not sure why that is?我发现如果我摆脱了捕获中的“terminate()”,它会起作用,但我不知道为什么会这样?
There are three outputs that are produced randomly:随机产生三个输出:
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.
Exception message.
Exception message.
Exception message.
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.
Exception message.
Exception message.
Exception message.
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.
PS Sorry, maybe for the incorrect question, I'm a beginner. PS对不起,也许问题不正确,我是初学者。
For starters, your regular cout
print goes to stdout
, but the "Terminating with..." message goes to stderr
.对于初学者,您的常规cout
打印会发送到stdout
,但“终止于...”消息会发送到stderr
。 What you observe stems from the fact that your terminal (or IDE) is reading these two output channels and presenting them in one place.您观察到的原因是您的终端(或 IDE)正在读取这两个 output 通道并将它们呈现在一个位置。 Depending on what algorithm your terminal/IDE uses to merge these two streams, it can happen that the stderr
message appears in the places you notice.根据您的终端/IDE 用于合并这两个流的算法, stderr
消息可能会出现在您注意到的地方。
If you instead point the streams toward the same file descriptor, your OS will take care of the merging.如果您将流指向相同的文件描述符,则您的操作系统将负责合并。 Run your program as follows:按如下方式运行您的程序:
./my_program 2>&1
Now your terminal will show the messages sequentially with no chance for accidental reordering.现在您的终端将按顺序显示消息,而不会意外重新排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.