Is it in good style do use cerr in situation described below?
try
{
cout << a + b;
}
catch(const IntException& e)
{
cerr << "Exception 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.
Therefore, if the message is an actual product of your program, you should use cout, if it's just a status message, use cerr. Of course, all this doesn't matter that much if what goes to the console is just a byproduct.
cerr is tied to the standard output stream cout (see ios::tie ), which indicates that cout 's buffer is flushed (see ostream::flush) before each i/o operation performed on cerr. By default, cerr is synchronized with stderr (see ios_base::sync_with_stdio ).
Standard error stream (cerr): cerr is the standard error stream which is used to output the errors. It is an instance of the ostream class. As cerr stream is un-buffered so it is used when we need to display the error message immediately and does not store the error message to display later.
After the cerr object is constructed, the expression ( cerr.flags & unitbuf) is non-zero, which means that any output sent to these stream objects is immediately flushed to the operating system. Also cerr.tie () == &cerr i.e. cerr.tie () returns &cerr which means that cerr.flush () is executed before any output operation on cerr.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With