ezpresso
ezpresso

Reputation: 8126

The error representation and handling

I am designing a cross-platform application protection library to communicate with a dongle. The dongle is able to send and receive blocks of data, to create and delete directories and files inside the dongle's internal file system, etc. To put it simple, the main dongle object has methods to implement all of these functionalities. Unfortunately, any of these methods may fail. Right now I am thinking about what to do if they do :)

The most obvious solution is to return a boolean type result from all of these methods to indicate if they fail or success. However, this leads to a loss of details about the nature of an error.

The next possible solution is to return an error code, but there will be more then 30 types of errors. Also, I will need to design a separate function to convert all of these return codes to a more readable string representation.

The third solution is to return a boolean type result, but to keep an error state object in the main dongle object so it will be possible to retrieve it using GetLastError() like method. I am considering about using this one.

Now is my question. Are there any other reasonable error representation and handling patterns and what do you suggest me to use in my case?

Thanks, Ilya

Upvotes: 0

Views: 150

Answers (2)

John Dibling
John Dibling

Reputation: 101456

Of the options you have presented, the best is to use return codes. Typically a return code of zero indicated success, and each other return code has its own positive integral value. 30 error conditions isn't many. As you've said, you'll have to write code to translate these codes to something human-readable, but you have to do this anyway.

I would consider writing an exception hierarchy to do this instead of error codes, however. Exceptions can be more expressive than return codes, and the code can be cleaner if done properly. You would typically design your library so that there is a different exception class for each type of error return condition, each derived ultimately from std::exception. The what() method gives you a place to put the human-message building, and the type of the exception itself describes the error.

There are those who will tell you that exceptions are "only" for exceptional circumstances, like your computer caught fire, or something. This is a hotly debated assertion. I'll tell you that is nonsense. Just because it is named "exception" doesn't mean your computer has to catch fire in order to use it. Exceptions give you a lot of benefits, one of the biggest being stack unwinding. Preventing yourself from using them simply because of some arbitrary line where errors are "bad enough" is silly.

Upvotes: 2

poy
poy

Reputation: 10507

You could also try using std::exception. It allows you to say what the error is and the nature behind it.

Upvotes: 0

Related Questions