[英]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.