Easy way to throw exceptions with sprintf-like message?

H

Henryk

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
 
M

mlimber

Henryk said:
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
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
 
M

Mathias Gaunard

Henryk said:
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.
 
S

Salt_Peter

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

mlimber

Salt_Peter said:
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
 
S

Salt_Peter

mlimber said:
Salt_Peter said:
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.
 
H

Henryk

mlimber said:
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.
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:)
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top