Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what should I do if I got a null pointer?

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?

like image 241
shengy Avatar asked Dec 11 '25 17:12

shengy


2 Answers

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.

like image 181
Luchian Grigore Avatar answered Dec 14 '25 09:12

Luchian Grigore


I would use these options in this order in case you don't want to throw exceptions

  1. boost::optional

  2. int GetSomeVal(int &ok) - make ok false if pointer is NULL

  3. return some error code if pointer is NULL (-1 for example)

like image 26
Andrew Avatar answered Dec 14 '25 08:12

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!