Supposing a method:
public boolean setAttribute(){
boolean re开发者_如何学Goturnval = false;
object = this.getObject; //suppose this returns null
for(Object obj : object.getObjectsForLoop()){ //<== this will fail
doSomething();
returnval = true;
}
return returnval;
}
Now, suppose this is called elsewhere, in a procedure. Will this method fail at it's fourth line and not return anything?
It will throw a NullPointerException
instead of returning anything
Read the Exceptions Trail of the Java Tutorial for more info. There's a pretty good explanation of the concept and process on this page: What Is an Exception?
If this fails to return a valid object:
object = this.getObject;
This won't return anything. It'll throw a NullPointerException:
for(Object obj : object.getObjectsForLoop()){
If object is null, the use of it in the iterator will trigger a NullPointerException - thats what you will get.
The method will complete abruptly with a NullPointerException
. In other words: it won't return anything.
Depends on what you mean by fail. In your case it looks like you mean throws NullPointerException
. In that case, the caller of setAttribute will also get the NullPointerException. If you don't handle NullPointerException at any place this will go all the back in the stack to main and terminate your program. If you handle NullPointerException, the catch block will be called.
This will result in NullPointerException
because the for
will attempt to obtain an iterator from a null
object.
精彩评论