Easy way to throw exceptions with sprintf-like message?

Discussion in 'C++' started by Henryk, Nov 21, 2006.

  1. Henryk

    Henryk Guest

    I did a lot of delphi GUI programming recently.

    In my experience most of the time you just want to throw a standard
    exception with a descriptive message. Then all calling functions can
    handle this exception as they like and finally show a message to the
    user or not. Only in a few occasions I need some special exception
    types to behave differently depending on the error.


    So what you basically do is
    // delphi syntax but the meaning should be clear
    try
    if ({some error check}) then
    // what a nice one-liner...
    raise Exception.CreateFmt('Error parsing line %d: Command unknown',
    nLine);
    except
    on E: Exception do ... show user E.Message in a message box
    end;

    I tried to achieve something similar in c++

    try {
    if (/*some error check*/) {
    // 3 lines needed and also not very readable...
    std::eek:strstream msg;
    msg << "Error parsing line " << nLine << ": Command unknown" <<
    std::ends;
    throw std::exception(msg.str());
    }
    }
    catch(std:exception e) {
    show user e.what() in a message box
    }

    I could write my own derived exception class that provides a
    sprintf-like function, but I was wondering if standard c++ provides
    something similar (and I couldn't find it).

    Btw, I like the printf formatting style over the stream style. The
    first one is better readable and it's much easier to implement mutiple
    languages.


    How do you do this kind of exception handling in your programs?

    Greets

    Henryk
     
    Henryk, Nov 21, 2006
    #1
    1. Advertising

  2. Henryk

    mlimber Guest

    Henryk wrote:
    > I did a lot of delphi GUI programming recently.
    >
    > In my experience most of the time you just want to throw a standard
    > exception with a descriptive message. Then all calling functions can
    > handle this exception as they like and finally show a message to the
    > user or not. Only in a few occasions I need some special exception
    > types to behave differently depending on the error.
    >
    >
    > So what you basically do is
    > // delphi syntax but the meaning should be clear
    > try
    > if ({some error check}) then
    > // what a nice one-liner...
    > raise Exception.CreateFmt('Error parsing line %d: Command unknown',
    > nLine);
    > except
    > on E: Exception do ... show user E.Message in a message box
    > end;
    >
    > I tried to achieve something similar in c++
    >
    > try {
    > if (/*some error check*/) {
    > // 3 lines needed and also not very readable...
    > std::eek:strstream msg;


    strstreams have been deprecated in favor of stringstreams. Use
    <sstream> to find them.

    > msg << "Error parsing line " << nLine << ": Command unknown" <<
    > std::ends;
    > throw std::exception(msg.str());
    > }
    > }
    > catch(std:exception e) {
    > show user e.what() in a message box
    > }
    >
    > I could write my own derived exception class that provides a
    > sprintf-like function, but I was wondering if standard c++ provides
    > something similar (and I couldn't find it).


    There's nothing standard, but you might also consider Boost.Format
    (http://boost.org/libs/format/index.html) for a more type-safe
    alternative to sprintf. Also consider that your exception class should
    not throw an exception (at least in its copy constructor or
    destructor), and so any class whose copy ctor itself might throw should
    not be used in an exception class either. If you do throw an exception
    in your copy-ctor, std::terminate() is called.

    > Btw, I like the printf formatting style over the stream style. The
    > first one is better readable and it's much easier to implement mutiple
    > languages.
    >
    > How do you do this kind of exception handling in your programs?


    See this paper by C++ exceptions guru Dave Abrahams:

    http://boost.org/more/error_handling.html

    He recommends that you delay message formatting until what() is called
    so that stack unwinding can be performed and some resources freed
    (which is helpful, e.g., when a resource allocation problem caused the
    exception). That means storing all the necessary parameters in your
    exception class, which could mean a lot of them. For non-resource
    allocation exceptions, I prefer to format the message in situ and have
    the exception carry around a plain old array of characters with the
    full message in it.

    Cheers! --M
     
    mlimber, Nov 21, 2006
    #2
    1. Advertising

  3. Henryk wrote:

    > I could write my own derived exception class that provides a
    > sprintf-like function, but I was wondering if standard c++ provides
    > something similar (and I couldn't find it).


    See boost.format.
     
    Mathias Gaunard, Nov 21, 2006
    #3
  4. Henryk

    Salt_Peter Guest

    Henryk wrote:
    > I did a lot of delphi GUI programming recently.
    >
    > In my experience most of the time you just want to throw a standard
    > exception with a descriptive message. Then all calling functions can
    > handle this exception as they like and finally show a message to the
    > user or not. Only in a few occasions I need some special exception
    > types to behave differently depending on the error.
    >
    >
    > So what you basically do is
    > // delphi syntax but the meaning should be clear
    > try
    > if ({some error check}) then
    > // what a nice one-liner...
    > raise Exception.CreateFmt('Error parsing line %d: Command unknown',
    > nLine);
    > except
    > on E: Exception do ... show user E.Message in a message box
    > end;
    >
    > I tried to achieve something similar in c++
    >
    > try {
    > if (/*some error check*/) {
    > // 3 lines needed and also not very readable...
    > std::eek:strstream msg;
    > msg << "Error parsing line " << nLine << ": Command unknown" <<
    > std::ends;
    > throw std::exception(msg.str());
    > }
    > }
    > catch(std:exception e) {
    > show user e.what() in a message box
    > }
    >
    > I could write my own derived exception class that provides a
    > sprintf-like function, but I was wondering if standard c++ provides
    > something similar (and I couldn't find it).
    >
    > Btw, I like the printf formatting style over the stream style. The
    > first one is better readable and it's much easier to implement mutiple
    > languages.
    >
    >
    > How do you do this kind of exception handling in your programs?
    >


    There is no restriction about how you implemet or catch exceptions. You
    could derive from std::exception, throw/catch a std::string,
    throw/catch an integer or even a Class object. You could embed an
    exception class as well and it doesn't have to be derived from
    std::exception or std::runtime_error.

    As long as you make some effort to catch those exceptions thrown by the
    implementation, you are free to experiment. As a simple example:

    #include <iostream>
    #include <stdexcept>

    class MyError : public std::exception
    {
    std::string s;
    public:
    MyError(std::string s_) : s("MyError Exception: " + s_) { }
    ~MyError() throw() { }
    const char* what() const throw() { return s.c_str(); }
    };

    int main()
    {
    try
    {
    throw MyError("testing...");
    }
    catch(const std::exception& e)
    {
    std::cerr << e.what() << std::endl;
    }
    }

    /*
    MyError Exception: testing...
    */
     
    Salt_Peter, Nov 21, 2006
    #4
  5. Henryk

    mlimber Guest

    Salt_Peter wrote:
    > There is no restriction about how you implemet or catch exceptions. You
    > could derive from std::exception, throw/catch a std::string,
    > throw/catch an integer or even a Class object.

    [snip]
    >
    > class MyError : public std::exception
    > {
    > std::string s;

    [snip]
    > };


    There are no language restrictions, but there are practical ones. See
    the warnings against such practices here:

    http://boost.org/more/error_handling.html

    Cheers! --M
     
    mlimber, Nov 21, 2006
    #5
  6. Henryk

    Salt_Peter Guest

    mlimber wrote:
    > Salt_Peter wrote:
    > > There is no restriction about how you implemet or catch exceptions. You
    > > could derive from std::exception, throw/catch a std::string,
    > > throw/catch an integer or even a Class object.

    > [snip]
    > >
    > > class MyError : public std::exception
    > > {
    > > std::string s;

    > [snip]
    > > };

    >
    > There are no language restrictions, but there are practical ones. See
    > the warnings against such practices here:
    >
    > http://boost.org/more/error_handling.html
    >
    > Cheers! --M


    Yep, thanks - no std::string.
     
    Salt_Peter, Nov 21, 2006
    #6
  7. Henryk

    Henryk Guest

    mlimber wrote:
    > Henryk wrote:
    > > I did a lot of delphi GUI programming recently.
    > >
    > > In my experience most of the time you just want to throw a standard
    > > exception with a descriptive message. Then all calling functions can
    > > handle this exception as they like and finally show a message to the
    > > user or not. Only in a few occasions I need some special exception
    > > types to behave differently depending on the error.
    > >
    > >
    > > So what you basically do is
    > > // delphi syntax but the meaning should be clear
    > > try
    > > if ({some error check}) then
    > > // what a nice one-liner...
    > > raise Exception.CreateFmt('Error parsing line %d: Command unknown',
    > > nLine);
    > > except
    > > on E: Exception do ... show user E.Message in a message box
    > > end;
    > >
    > > I tried to achieve something similar in c++
    > >
    > > try {
    > > if (/*some error check*/) {
    > > // 3 lines needed and also not very readable...
    > > std::eek:strstream msg;

    >
    > strstreams have been deprecated in favor of stringstreams. Use
    > <sstream> to find them.


    Oh, good to know! I just started to play with the STL in favour of the
    old c functions, which I am used to.

    >
    > > msg << "Error parsing line " << nLine << ": Command unknown" <<
    > > std::ends;
    > > throw std::exception(msg.str());
    > > }
    > > }
    > > catch(std:exception e) {
    > > show user e.what() in a message box
    > > }
    > >
    > > I could write my own derived exception class that provides a
    > > sprintf-like function, but I was wondering if standard c++ provides
    > > something similar (and I couldn't find it).

    >
    > There's nothing standard, but you might also consider Boost.Format
    > (http://boost.org/libs/format/index.html) for a more type-safe
    > alternative to sprintf. Also consider that your exception class should
    > not throw an exception (at least in its copy constructor or
    > destructor), and so any class whose copy ctor itself might throw should
    > not be used in an exception class either. If you do throw an exception
    > in your copy-ctor, std::terminate() is called.
    >


    Boost is a little overkill for my small programm, I guess :eek:)

    > > Btw, I like the printf formatting style over the stream style. The
    > > first one is better readable and it's much easier to implement mutiple
    > > languages.
    > >
    > > How do you do this kind of exception handling in your programs?

    >
    > See this paper by C++ exceptions guru Dave Abrahams:
    >
    > http://boost.org/more/error_handling.html


    That is a very helpful link. The help files never tell you what is good
    practice. So I really appreciate such papers.

    > He recommends that you delay message formatting until what() is called
    > so that stack unwinding can be performed and some resources freed
    > (which is helpful, e.g., when a resource allocation problem caused the
    > exception). That means storing all the necessary parameters in your
    > exception class, which could mean a lot of them. For non-resource
    > allocation exceptions, I prefer to format the message in situ and have
    > the exception carry around a plain old array of characters with the
    > full message in it.


    That is exactly what I do most of the time in my delphi program. And
    exactly the in situ formatting is much easier in delphi with the
    sprintf-style constructor CreateFmt. As an excersize I will write my
    own exception class that allows variable arguments and behaves like
    printf.

    Cheers

    Henryk
     
    Henryk, Nov 22, 2006
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kerri
    Replies:
    2
    Views:
    13,122
    Kevin Spencer
    Oct 27, 2003
  2. Replies:
    15
    Views:
    7,770
    Roedy Green
    Sep 8, 2005
  3. Robert
    Replies:
    22
    Views:
    681
    Kevin McMurtrie
    Jun 12, 2008
  4. Emanuele D'Arrigo

    To throw or to throw not?

    Emanuele D'Arrigo, Nov 14, 2008, in forum: Python
    Replies:
    6
    Views:
    351
    Emanuele D'Arrigo
    Nov 15, 2008
  5. Kenneth McDonald
    Replies:
    9
    Views:
    103
    Kenneth McDonald
    Oct 13, 2006
Loading...

Share This Page