3

I know the general matter has been discussed in this stackoverflow topic already (constructors never return null), but considering its significance in this concrete matter, I would like to know if the official Android documentation of the SoundPool constructor is wrong then:

Constructor. Returns a SoundPool object, or null if creation failed

I'm asking this because we're talking about no less than the official documentation of Android that has been up for years (in case of SoundPool).

Checking the Android source code, the SoundPool throws a RuntimeException in case of an error in constructor. (The pre-2.3 Android did not even throw an exception.) Perhaps the documentation tries to express that if the exception is caught, then the variable where I intended to store the object reference remains null? In this case, the doc is still very poorly worded. Am I missing something?

EDIT: considering this might not be a very content-rich question (even though it may be useful -- see my comments), a simple Yes or No would be sufficient, and then the thread can get closed. I want to make sure I haven't overlooked anything.

Community
  • 1
  • 1
Thomas Calc
  • 2,994
  • 3
  • 30
  • 56
  • Excuse me, but why the "off-topic" and "not a real question" votes? It is definitely on-topic. It may be an exact duplicate (and may get closed as such), but definitely a clearly defined question. And "not a real question"? It is very clear: is the official Android doc wrong, or correct? This is a real and clear programming-related question. – Thomas Calc Nov 20 '12 at 18:55
  • And **useful** as well, especially for starter Android programmers: imagine how much code we'll see where the programmer null-checks the reference of a newly instantiated SoundPool... – Thomas Calc Nov 20 '12 at 18:57
  • Even if the beginner programmers knows that constructors cannot return null, they might add the null-check to follow the doc for 100%. And then such a code gets on the internet, spreads, and misleads complete starters. – Thomas Calc Nov 20 '12 at 19:03

1 Answers1

1
  1. Constructors cannot return null. They can throw exceptions, but they cannot return anything but the object which they create if successful.
  2. As you have found, SoundPool may throw an exception in it's constructor. You can ignore it. They specifically chose to throw a RuntimeException (on 2.3+) as opposed to a checked exception which indicates the API designers consider this a good enough reason to crash an app and that does not need to be routinely handled.
  3. If you really must handle the exception then I would simply notify the user and quit immediately.

So no, it can't return null. But if you handle the exception then yes, your reference to the object will be null because the constructor did not complete.

Joseph Earl
  • 23,351
  • 11
  • 76
  • 89