I come from a c++ background and I find myself constantly doing this in java:
SomeClass sc=new SomeClass();
if(null!=sc)
{
sc.doSomething();
}
What I want to know is what will be in the variable sc if the constructor fails for some reason (like maybe not enough memory). I can’
t find a straight answer, and I am worried that I am just wasting my time because maybe if the new operator fails would the program just crash anyway?
The Java Specification Language 3rd Edition covers your question thoroughly:
So it’s simply not possible for a
newexpression to returnnull. Whatever is returned, if the execution completes normally, will always be a validinstanceofwhatever class was instantiated.Handling exceptions
Generally speaking, possible exceptions are usually handled with a
try-catchblock:In your case, you may consider putting
new SomeClass()in atryblock with a correspondingcatch (OutOfMemoryError e), but this is highly atypical. Unless you plan to do something meaningful when this happens, in most typical scenarios it’s best to notcatchanyErrorthat may occur during your program execution.From the documentation:
Related questions
See also