if 语句检查 null 但仍抛出 NullPointerException [英] if statement checks for null but still throws a NullPointerException

查看:22
本文介绍了if 语句检查 null 但仍抛出 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中.

public class Test {
     public static void testFun(String str) {
         if (str == null | str.length() == 0) {
             System.out.println("String is empty");
         } else { 
             System.out.println("String is not empty");
         }
     }
     public static void main(String [] args) {
         testFun(null);
    }
}

我们将null 值传递给函数testFun.编译得很好,但在运行时给出了一个 NullPointerException,这是我没想到的.为什么它会抛出异常,而不是将 if 条件评估为 true 并打印String is empty"?

We pass a null value to the function testFun. Compiles fine, but gives a NullPointerException in runtime, which I did not expect. Why is it throwing an exception, rather than evaluating the if condition to true and printing "String is empty"?

假设传递给 testFun 的实际参数的值是从某个进程生成的.假设该进程错误地返回了一个 null 值并将其提供给 testFun.如果是这种情况,如何验证传递给函数的值是否为空?

Suppose the value of the actual argument being passed to testFun is generated from some process. Assume that mistakenly a null value is returned by that process and is fed to testFun. If such is the case, how does one validate that the value passed to the function is null or not?

一种(奇怪的)解决方案可能是将形式参数分配给函数内部的某个变量,然后对其进行测试.但是如果有很多变量传递给函数,那可能会变得乏味和不可行.那么,在这种情况下如何检查空值呢?

One (weird) solution may be by assigning the formal parameter to some variable inside the function and then testing it. But if there are many variables passed to the function, that might become tedious and unfeasible. So, how does one check for null values in such a scenario?

推荐答案

编辑显示了有效的代码和无效的代码之间的区别.

The edit shows exactly the difference between code that works and code that doesn't.

此检查总是评估两个条件,如果 str 为空,则抛出异常:

This check always evaluates both of the conditions, throwing an exception if str is null:

 if (str == null | str.length() == 0) {

而这(使用 || 而不是 |)是短路 - 如果第一个条件评估为 true,第二个不被评估.

Whereas this (using || instead of |) is short-circuiting - if the first condition evaluates to true, the second is not evaluated.

请参阅 JLS 的第 15.24 节,了解||第 15.22.2 节 用于二进制 |.15.24 节的介绍是很重要的一点:

See section 15.24 of the JLS for a description of ||, and section 15.22.2 for binary |. The intro to section 15.24 is the important bit though:

条件或运算符 ||运算符就像 |(第 15.22.2 节),但仅当其左侧操作数的值为 false 时才评估其右侧操作数.

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

这篇关于if 语句检查 null 但仍抛出 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆