shengy
shengy

Reputation: 9749

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?

Upvotes: 3

Views: 126

Answers (3)

Andriy
Andriy

Reputation: 8604

It highly depends on the function specification.

ptr==NULL may be a valid but exceptional input to the function, for example, it was caused by incorrect input data to the program. Then the best way to handle it is to return an error code or throw an exception which is intended to be handled up the call chain.

In other cases, ptr==NULL could never happen by design, but only because of a bug elsewhere. Then the best way is to log the error and terminate the program.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

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.

Upvotes: 7

Andrew
Andrew

Reputation: 24846

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)

Upvotes: 1

Related Questions