Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Easy way to throw exceptions with sprintf-like message?

Reply
Thread Tools

Easy way to throw exceptions with sprintf-like message?

 
 
Henryk
Guest
Posts: n/a
 
      11-21-2006
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: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

 
Reply With Quote
 
 
 
 
mlimber
Guest
Posts: n/a
 
      11-21-2006
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: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

 
Reply With Quote
 
 
 
 
Mathias Gaunard
Guest
Posts: n/a
 
      11-21-2006
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.

 
Reply With Quote
 
Salt_Peter
Guest
Posts: n/a
 
      11-21-2006

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: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...
*/

 
Reply With Quote
 
mlimber
Guest
Posts: n/a
 
      11-21-2006
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

 
Reply With Quote
 
Salt_Peter
Guest
Posts: n/a
 
      11-21-2006

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.

 
Reply With Quote
 
Henryk
Guest
Posts: n/a
 
      11-22-2006

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

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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
To throw or to throw not? Emanuele D'Arrigo Python 6 11-15-2008 04:12 PM
Any way to get lists to throw exceptions on incorrect accesses? Kenneth McDonald Ruby 9 10-13-2006 09:22 PM
JNI's throw new does not throw an exception yarona@m-sys.com Java 15 09-08-2005 08:36 AM
Throw Exception Vs Throw New Exception Kerri ASP .Net 2 10-27-2003 02:13 PM
JavaMail does not throw exceptions?? moo moo Java 3 10-22-2003 09:27 PM



Advertisments