◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
空指针异常 (npe),表示为 java.lang.nullpointerexception,当 java 程序尝试在需要对象的地方使用空引用时发生。它是 java 中最常见的运行时异常之一,通常是由于尝试以下操作引起的:
string str = null; str.length(); // causes nullpointerexception
myobject obj = null; obj.field = 5; // causes nullpointerexception
int[] arr = null; arr[0] = 10; // causes nullpointerexception
mymethod(null); // if mymethod doesn't handle null, it might cause an npe
示例堆栈跟踪:
exception in thread "main" java.lang.nullpointerexception at mainclass.main(mainclass.java:10)
查看 mainclass.java:10 来确定问题。
if (myobject != null) { myobject.dosomething(); }
optional<string> optionalstr = optional.ofnullable(str); optionalstr.ifpresent(s -> system.out.println(s.length()));
this.name = objects.requirenonnull(name, "name must not be null");
string str = somemethod() != null ? somemethod() : "";
public void setName(@NonNull String name) { this.name = name; }
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。