java.lang.NullPointerException
我对一个值为空和不为空的值执行一个条件。 当这个值为空时,我得到了java.lang.NullPointerException
。
我该如何处理这个问题才能消除这个异常?
我需要值何时为空以及何时不为空的条件。
I do a condition with a value when it is null and when it is not null.
The time where this value is null I got the java.lang.NullPointerException
.
How could I deal with this in order to dismiss this exception?
I need the condition when the value is null and when it is not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您尝试使用
null
变量调用方法时,您会收到NullPointerException
。简单的例子:因此,在调用变量的任何方法之前,您应该检查变量是否为
null
,例如:请注意,
NullPointerException
通常很容易解决。仔细查看异常的堆栈跟踪;它准确地告诉您异常发生在代码的哪一行。检查该行代码中哪些内容可能为null
,并检查您是否正在对可能为null
的内容调用方法。添加一个检查(或防止相关事物以另一种方式为null
)。You get a
NullPointerException
when you try to call a method using a variable that isnull
. Simple example:So you should check if the variable is
null
before calling any method on it, for example:Note that a
NullPointerException
is usually easy to solve. Carefully look at the stack trace of the exception; it tells you exactly in which line of your code the exception happens. Check what could benull
in that line of code, and check if you're calling a method on something that might benull
. Add a check (or prevent that the relevant thing can ever benull
in another way).只需正确检查值是否为
null
。诸如之类的条件永远不会引发 Null
RefePointerException。仅当您尝试访问null
引用指向的任何内容时,才会出现异常。因此调用方法或访问对象的其他实例成员是不可能的。Simply do a proper check for the value being
null
. A conditional such aswill never raise a Null
RefePointerException. It's only if you try accessing whatever anull
reference points to that you get the exception. So calling methods or accessing other instance members of the object is out of the question.使用 if 检查变量是否不为空,然后使用 else 代码块检查变量是否为空。
仅当您尝试使用空值时才会抛出空指针。
例如,
但是您应该始终避免可能出现空指针的情况。
Use an if to check for the variable not being null and then use an else code block for when it is null.
The null pointer is only thrown when you try and use the null value.
For example,
But you should always avoid a situation where a null pointer could occur.
正如其他发帖者所述,如果您不希望此处的 s 引用为空,那么首先修复导致引用为空的错误。但是,如果引用可以为 null 是有效的,您还可以使用三元运算符(Java 5 上)执行以下操作。
注意:括号是可选的,但在我看来,它们使其更具可读性。
As stated by other posters, if you do not expect the s reference to be null here then fix the bug that causes the reference to be null in the first place. However, if it is valid that the reference could be null, you can also do the following using the ternary operator (Java 5 on)
Note: the brackets are optional, but they make it a bit more readable in my opinion.
这是一个非常令人困惑的问题,但是:
It is a really confusing question, but: