-
January 5th, 2009, 05:12 PM
#1
Easily create string message for exception
Hi,
For a long time I’ve wondered if there is a simplier way to do this, but I’ve never found it. If I have the following code:
Code:
void SomeClass::SomeMethod(const char *arg) {
If (someTestOfTheArgFailed)
throw std::invalid_argument (“Invalid argument ‘” + arg + “’”);
}
Now obviously the above code doesn’t work, because I can’t do “Invalid argment ‘” + arg. The alternative would be to do:
Code:
If (someTestOfTheArgFailed) {
std::string s;
s += " Invalid argument '";
s += arg;
s += "'";
throw std::invalid_argument (s);
}
This works but has needlessly added extra lines.
It would be cool if I could use some kind of printf syntax, or use operator<<.
Is there some clever trick I can use to do this all on one line still? Perhaps a function or macro I could develop? This is just so I can make my error handling code neater. I don't want to have 4-5 lines for each error message.
Thanks
Andrew
-
January 5th, 2009, 05:15 PM
#2
Re: Easily create string message for exception
Code:
void SomeClass::SomeMethod(const char *arg) {
If (someTestOfTheArgFailed)
throw std::invalid_argument (std::string(“Invalid argument ‘”) + arg + “’”);
}
I think Boost has something similar to printf that you can use. However, I'd just do the above for starters....
-
January 5th, 2009, 08:35 PM
#3
Re: Easily create string message for exception
The easiest way I've found is to make your own exception class that takes a printf style format string and variadic args. I can't recall offhand though if variadic constructors are part of the standard or a MSVC extension...
Anyway, what I usually use is something like:
Code:
#include <stdexcept>
#include <cstdarg>
#include <cstdio>
class MyError
: public std::runtime_error
{
public:
static const size_t BUFSIZE = 2048;
MyError(const char* format, ...)
: std::runtime_error("")
{
va_list args;
char buffer[BUFSIZE];
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
std::runtime_error::operator =(std::runtime_error(buffer));
}
};
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|