Error Handling
When you write code, you might want the error to throw something.
Formally learned this in CS247.
There are several ways to handle errors.
Option 1: Sentinel values
Reserve some values, -1
, INT_MIN
to signal errors
Problem: reduces what we can return, can’t return -1
in a regular scenario. Not clear for a general type T
what values we should pick as sentinels.
Option 2: Global Variables
Create some global variable that is set when an error occurs (in C, int errno
, which can be queried for errors with standard functions).
Problem: limited # of errors, might be overwritten
Option 3: Bundle in a struct
We can do something like this
Best so far, but still not ideal. Wrap our return types in this struct
, all return types are larger than needed. Awkward to access data field.
These are all approaches that C
users end up using. C++ however has a language feature for dealing with errors: Exception.
Learning from Hemal Shah
Within NVIDIA, we actually bundle inside a struct.
If you look at something like TinyXML, they use an Enum.
enum XMLError {
XML_SUCCESS = 0,
XML_NO_ATTRIBUTE,
XML_WRONG_ATTRIBUTE_TYPE,
XML_ERROR_FILE_NOT_FOUND,
XML_ERROR_FILE_COULD_NOT_BE_OPENED,
XML_ERROR_FILE_READ_ERROR,
XML_ERROR_PARSING_ELEMENT,
XML_ERROR_PARSING_ATTRIBUTE,
XML_ERROR_PARSING_TEXT,
XML_ERROR_PARSING_CDATA,
XML_ERROR_PARSING_COMMENT,
XML_ERROR_PARSING_DECLARATION,
XML_ERROR_PARSING_UNKNOWN,
XML_ERROR_EMPTY_DOCUMENT,
XML_ERROR_MISMATCHED_ELEMENT,
XML_ERROR_PARSING,
XML_CAN_NOT_CONVERT_TEXT,
XML_NO_TEXT_NODE,
XML_ELEMENT_DEPTH_EXCEEDED,
XML_ERROR_COUNT
};