473,379 Members | 1,344 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

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 11619
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Kenny Cutter | last post by:
Hi group, I am quite new to exceptions in .NET and I am a bit confused of how to use the inner exceptions. Could anyone explain? Let's say I have a function that takes a double (X) that is not...
5
by: Dave | last post by:
Hello all, Unfortunately, the reference I have is a bit slim on describing how to create user-defined exceptions derived from std::exception. I think what I have below will work, but is it the...
4
by: Jurko Gospodnetić | last post by:
Hi all. I was wondering. Can the standard basic_string<> c_str() member function throw any exceptions? Is it perhaps implementation dependent? I tried checking the standard and as far as I...
21
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How...
1
by: Bruno van Dooren | last post by:
Hi, i am using some STL containers in a library of mine. how can i see which exceptions can occur when doing something with those containers (adding an elemnt for example) i have looked in...
8
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an...
18
by: Denis Petronenko | last post by:
Hello, in the following code i have segmentaion fault instead of exception. Why? What i must to do to catch exceptions in such situation? Used compiler: gcc version 3.3.6 (Debian 1:3.3.6-13) ...
5
by: Olaf Rabbachin | last post by:
Hi folks, I have a (VB.Net-) DLL that I'm using from MS Access 2003. Everything's pretty fine except for one thing - When I throw or pass on exceptions from within the .Net-DLL, all I get is Err...
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
13
by: mike3 | last post by:
Hi. (crossposted because the program is in C++ and some C++-related elements are discussed, hence comp.lang.c++, plus general program design questions are asked, hence comp.programming.) I'm...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.