Archived

This topic is now archived and is closed to further replies.

stodge

Returning error codes and exceptions

Recommended Posts

I''m a procedural developer coming to terms with C++ and OOP. At the moment I''m torn between when to use exceptions and when to just return error codes. For example, I''m writing a C++ networking library that wraps Winsock. Currently my code for error detection is like this:
	mSocket = socket(AF_INET, SOCK_STREAM, 0); 
	if (mSocket == HB_INVALID)
	{
		hbNetEngine::getInstance()->setError(getLastError());
		closeConnection();
		return HB_FALSE;
	} 
So I return the error to the application from the library and deal with it there. But I also had this funky idea of implementing exceptions, so I included:
	HBhost* hostent = gethostbyname(addr);
	ASSERT(hostent, NULL, "Error looking up remote hostname."); 
The ASSERT macro wraps try and catch, and executes a custom exception handler that basically cleanly shuts down the application an exits. The only drawback here is that the code doesn''t set the network engine error code, so that the application doesn''t really know what went wrong. Should I use a mix of the two, or stick with just one? I initially implemented everything using return codes, but now I''m not sure what to do! Thanks

Share this post


Link to post
Share on other sites
quote:
The ASSERT macro wraps try and catch


#define ASSERT(x,y,z) \
try \
{ \
if (x == y) \
{ \
throw z; \
} \
} \
catch (exceptionType str) \
{ \
hbExceptionHandler::getInstance()->raiseException(str); \
}


Yes I have.

Share this post


Link to post
Share on other sites
could be wrong, but I think ASSERT is only defined for debug builds. So if it''s a condition that could happen in a release, it won''t be handled.

Generally, I use exceptions like this
if it''s a condition that is "normal" to the flow of execution (i.e. a writing a string into a number field) use return codes.

If it''s a critical error, (lack of system resources etc) use exceptions.

that''s just a personal style thing though. If it''s really performance critical, and you want to continue on after a certain condition, exceptions will slow you down.

Share this post


Link to post
Share on other sites