A simple way to clarify the requirements of your exception class, is to look at each
throw
statement, and imagine it were a
return
statement instead.
In this case, all
throw
statements look the same: they "return" an object of a class called SocketException, and initialize it with a single argument of type
const char*
.
I haven't tried it but I believe the most simple solution would be:
typedef const char* SocketException;
I. e. rather than define a new class, you use a pre-existing type. However, this could be problematic if you have more than one Exception type based on the same pre-existing type, because then you wouldn't be able to distinguish between the two types of errors.
So the next best solution would be:
struct SocketException {
const char* message;
SocketException(const char* text) {
message = text;
}
};
Whether you make it a struct or a class doesn't matter, but if in the above example your member variable
message
were declared
private
, you'd need to add an accessor function as well.
Even better would be a constructor that doesn't simply copy a pointer, but creates a copy of the string. That would allow you to throw an exception with a constructed message that is stored in a temporary variable:
#include <string>
class SocketException {
public:
std::string message;
SocketException(const char* text) {
message = text;
}
};
void foo() throw SocketException {
char buffer[30]; static int count = 0;
sprintf(buffer, "foo called %d times!", count);
++count;
throw SocketException(buffer);
}
Note that the
SocketException
object will be constructed before leaving the function, i. e. while
buffer
can still be accessed safely. If you would store only the pointer, accessing the message would cause a run-time error.