In Java, if a null pointer is very rare, it is better to use catch instead of if

When cleaning some of my Android apps, I found a null pointer exception in the developer console that never happened, and I assume this is a rare race condition.

For those who do not know this: Android allows the user to report failures (iE uncaught exception) back to the developer.

I already began to print the infamous if (… != null)when it occurred to me: There are only three reports. . This is very rare.

So, I ask myself: in this situation and performance wise: Wouldn't it be better to exclude a null pointer instead of an exception?

Given that if will be evaluated every time.

+3
source share
5 answers

Not to sound like a fanatic or a limited person, but I firmly believe that NPE should never be allowed in the first place ! In my opinion, catching an NPE is a very bad practice. This means that you do not fully understand how your code works.

The first thing you should always do before using any input is checking for a null value.

+8
source

How often "every time"? Once per load? Every minute? 1000 times per second?

In any case, the test is for obj == nullabout the same cheap operation as you can get, and, of course, cheaper than handling exceptions.

- . , , .

+3

. , , , , . - , NullPointerException , .

+2

, , ? , "if (...!= Null)" , .

try catch, ( - , ), , , , .

, , , ( , ).

0

, ,

It sounds like an error and just catching the exception sounds like you intend to ignore the error, not fix it. Find out where these null values ​​come from and fix them; don't let null pointers apply to code that can't handle them.

0
source

All Articles