[英]Is there any chance of ClassCastException/IllegalStateException with this java code?
[英]Is there any chance of this code printing null?
String readwidget(int a, int b){
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget.getText() != null){
Task.sleep(10);
System.out.println(readwidget.getText());
return readwidget.getText();
}
Task.sleep(10);
return GOT_NULL;
}
while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {
readFirstWidget = readwidget(1184, 13);
Task.sleep(50,80);
}
此段代码在while(50次中的1次)中一次使用nullpointerexception崩溃,并且在该时间点不应打印null。 谁能帮我找出原因吗? 提前致谢。
您在注释中提到Widgets.get(a,b)
可以返回null
。 鉴于此,您需要通过在实际调用任何实例方法之前检查方法的返回值是否为null
来防范这种可能性。 您没有这样做,因此在这种情况下会崩溃。
您需要做的就是添加null检查,您的代码应该可以:
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget != null && readwidget.getText() != null) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.