Is it in good style do use cerr in situation described below?
try
{
cout << a + b;
}
catch(const IntException& e)
{
cerr << "E开发者_Python百科xception caught: " << typeid(e).name(); //using cerr not cout
}
catch(...)
{
cerr << "Unknown exception.";//using cerr not cout
}
or cout should be used? See comments in code.
stderr
is the traditional stream to send error messages (so that the OS/shell/whatever can capture error messages separately from "normal" output), so yes, use std::cerr
!
I make no comment as to whether catching an exception simply to print it out is any better than simply letting the exception propagating out of your application...
Yes, because while by default they both go to the terminal, you could change where their output is directed, and you may wish cerr
to go to a log file while cout
continues to just go to stdout
.
Essentially it gives you more control over where different output goes if you want it now or in the future.
Sure, it's good to use cerr there. You can redirect cerr differently from cout, sometimes that helps you to highlight problems that could go buried in a huge cout log file.
One detail to keep in mind is that sending output directly to the terminal (with either cout or cerr), you do limit your ability to test for your error messages. It's always worth posing the question "How do I unit test this?".
精彩评论