Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shall I use cerr

Tags:

c++

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.

like image 281
There is nothing we can do Avatar asked Feb 20 '11 17:02

There is nothing we can do


People also ask

When to use Cout and when to use Cerr?

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.

How does Cerr work in iOS?

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 ).

What is the use of Cerr in ostream?

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.

How to flush the output of a Cerr object?

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.


2 Answers

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...

like image 88
Oliver Charlesworth Avatar answered Oct 11 '22 13:10

Oliver Charlesworth


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.

like image 20
Andrew Marshall Avatar answered Oct 11 '22 13:10

Andrew Marshall