468,247 Members | 1,440 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,247 developers. It's quick & easy.

Easy way to throw exceptions with sprintf-like message?

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

Nov 21 '06 #1
6 11112
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::ostrstream msg;
strstreams have been deprecated in favor of stringstreams. Use
<sstreamto 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

Nov 21 '06 #2
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.

Nov 21 '06 #3

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

Nov 21 '06 #4
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

Nov 21 '06 #5

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.

Nov 21 '06 #6

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::ostrstream msg;

strstreams have been deprecated in favor of stringstreams. Use
<sstreamto 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 :o)
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

Nov 22 '06 #7

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Kenny Cutter | last post: by
5 posts views Thread by Dave | last post: by
4 posts views Thread by Jurko Gospodnetić | last post: by
21 posts views Thread by mihai | last post: by
1 post views Thread by Bruno van Dooren | last post: by
18 posts views Thread by Denis Petronenko | last post: by
5 posts views Thread by Olaf Rabbachin | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by kermitthefrogpy | last post: by
reply views Thread by zattat | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.