简体   繁体   中英

Why does Java have NullPointerException's?

Why does Java throw an exception when you call a method on a null object? From what I understand, exceptions indicate some 'recoverable' error. However, I can't see a situation where you would wrap a method call in a try block, and then catch the NullPointerException . Couldn't you just check whether the object is null before making the method call? It seems like if you try to call a method on a null reference, the program should abort and crash immediately, since that indicates a programmer error rather than a 'recoverable' error.

From what I understand, exceptions indicate some 'recoverable' error.

Well, that's up to interpretation and the exception in question. In many cases, you cannot really do much.

But even if you cannot really do much, you probably don't want to crash the whole program. Logging (or even ignoring) the error and moving on is an appropriate response here.

However, I can't see a situation where you would wrap a method call in a try block, and then catch the NullPointerException.

Why not?

Couldn't you just check whether the object is null before making the method call?

Sure. That's an extremely common thing to do.

Unfortunately, it's also an extremely common thing to forget. That would indeed be a programming error. But even programming errors need to be handled gracefully, especially when they are so common.

It seems like if you try to call a method on a null reference, the program should abort and crash immediately,

That's what exceptions are used for.

The caller can then decide if they want to try to do something about it or just crash.

since that indicates a programmer error rather than a 'recoverable' error.

That is also up to interpretation and the special case. The programmer cannot be held responsible for arguments that are supposed (per API spec) to be not-null being null, for example.


A better question is maybe "Why does Java have Null?".

Because of all the problems it causes (programs crashing with NPE or even worse behaviour), Null has been called a Billion Dollar Mistake , and some newer languages like Scala or Rust try to fix it by not allowing Null values (instead you have to explicitly wrap the value in an Optional structure).

RuntimeException s generally aren't recoverable for a particular operation , and that's why you're not required to catch them, but an entire Web server shouldn't crash because a bug in one spot somewhere used a null when it shouldn't have. NullPointerException allows the program's tooling to note the error and report it appropriately while allowing other parallel operations to continue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM