When is it wise to catch a NullPointerException?

I think that most of the time, if not always, we can avoid exceptions from the null pointer by checking if the object is null before sending a message to it.

When is it wise then to catch a NullPointerException instead of checking for null pointers?

+3
source share
5 answers

Although technically a RuntimeException such as NullPointerException is the same as checked exceptions such as IOException, their philosophy is very different. In short, checked exceptions there allow you to solve problems that are beyond the control of programmers, such as network crashes or missing files. The intended use of excluded exceptions is to catch programming errors.

Given that they exist to catch programming errors, a NullPointerException and other unchecked exceptions should almost never be caught. Instead, a programming error should be fixed that allowed them to be thrown.

+6
source

- . NPE. null , "return Collections.emptyList();" null.

+5

. NPE ( ), null.

+2

, , . , , NullPointerException, API, , , . NullPointerException .

+2
Peter is right, it's more expensive. Although there are times when you do not want to check and just catch the null pointer, for example, embed a scripting language interpreter in the JVM. The expression evaluation code will be too confusing if you check for null everywhere.
+1
source

Source: https://habr.com/ru/post/1774618/


All Articles