473,811 Members | 3,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Creat eFmt('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:excep tion 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 11643
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.Creat eFmt('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:excep tion 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.Creat eFmt('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:excep tion 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_er ror.

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::st ring s_) : s("MyError Exception: " + s_) { }
~MyError() throw() { }
const char* what() const throw() { return s.c_str(); }
};

int main()
{
try
{
throw MyError("testin g...");
}
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.Creat eFmt('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:excep tion 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
1684
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 supposed to be less or equal to zero. Let's call this function DoSomething. Also let's say that this function in turn calls another function doing something with X.
5
6779
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 way the mechanism was intended to be used? Thanks, Dave
4
4510
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 can see it is implementation dependent with no guarantees what so ever, but I was hoping I may have missed something... :-)
21
4446
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 can we avoid throwing exceptions? If we already have an abject witch was initialized wit _create_ we will be forced to call create in copy constructor and to throw exceptions from it. Have a nice day,
1
1287
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 the MSDN collection, but class members lists nothing, and the specific functions also don't mention anything. am i looking in the wrong place or doi have to find my way through the STL
8
2260
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 exception should be thrown only in exceptional situations. It turned out that each of my colleagues had their own interpretation about what an "exceptional situation" may actually be. First of all, myself I’m against using exceptions extensively,...
18
2981
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) int main() { try{ int* p = NULL; *p = 4;
5
1764
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 #440 ("Automation Error"). I'm passing on exceptions like this: Throw ex .... and I'm throwing my own exceptions like this:
6
3571
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 uncaught exception. How to catch an exception that happened before main() try { ... } catch (...) { ... } block? Is there a way?
13
2573
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 making this bignum package in C++. I'm wondering though on how to handle the errors. Right now most operations routines return error codes if they fail -- but some routines they use inside them, or overloaded operators, will throw exceptions on...
0
9724
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10394
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9201
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5552
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.