The main thing is I don't know the best practice of handling null pointers.
here is the code:
int GetSomeVal()
{
if(ptr)
{
return *ptr
}
else
{
// What here?
// Should I return 0? or -1 or throw an exception?
}
}
I got this question because in google's c++ style-guide, it doesn't recommand us to use exceptions, and this may be another topic.
If I should use exceptions, does that mean I have to design an exception class an throw it? If I should not use exceptions, what is the best practice?
If it makes sense for ptr to be NULL, you shouldn't throw an exception. Exceptions are used to indicate something went wrong.
If ptr is NULL because something went wrong, by all means, throw an exception.
Google's code style is to be used by Google. They prohibit lots of things (like reference arguments, exceptions, etc.) that are normally used in any high-level OO language. You shouldn't obey it unless you work for Google.
You could design your own exception class, derive it from std::exception, and throw that from the code.
Also, from your code, ptr is a member. If it was supposed to get initialized in the constructor and it didn't, perhaps you should throw the exception from the constructor. There's no use in having an un-usable object.
I would use these options in this order in case you don't want to throw exceptions
boost::optional
int GetSomeVal(int &ok) - make ok false if pointer is NULL
return some error code if pointer is NULL (-1 for example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With