Shall I use cerr
Asked Answered
S

4

11

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.

Slavin answered 20/2, 2011 at 17:34 Comment(2)
It is a bad idea to catch (...) without either rethrowing the exception or terminating the program. You have no idea what the exception is and there is absolutely no way to know whether it is safe to continue execution.Quickman
@James and do you have any idea what I need that for?Slavin
S
19

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

Shoddy answered 20/2, 2011 at 17:36 Comment(0)
L
5

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.

Louis answered 20/2, 2011 at 17:37 Comment(2)
You may want to reword that; both stderr and stdout typically get redirected to the terminal output; this is not the same as saying that "stderr goes to stdout"!Shoddy
Thanks, sorry for the slip-up. Though technically if it's the same place it's not wrong but really it is. (I'm not deriding you, but we're programmers! Weird technicalities is everything ;))Louis
R
1

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.

Revolutionary answered 20/2, 2011 at 17:37 Comment(0)
R
1

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

Remunerative answered 20/2, 2011 at 19:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.