[英]How to suppress null pointer access warning in java?
我正在使用 Eclipse IDE。
我有一個拋出NullPointerException
的代碼,我正在使用try/catch
block
處理異常
這是我的代碼 -
String name = null;
int length = 0;
try {
length = name.length();
System.out.println("Number of letters in name: " + length);
} catch(NullPointerException e) {
System.out.println("NullPointerException occured");
}
System.out.println("I am being executed");
在具有identifier
length
的行上的try
block
,我收到警告 -
Null pointer access: The variable name can only be null at this location
我試圖通過使用來抑制警告 -
@SuppressWarnings("all")
length = name.length();
在具有identifier
length
的行上,我遇到了錯誤 -
Multiple markers at this line -
- Syntax error on token "length", VariableDecalaratorId expected after this token
- Null pointer access: The variable name can only be null at this location
- length cannot be resolved to a type
如何解決這個問題?
我不希望我的程序顯示此警告,因為我知道我在做什么。
感謝@Slaw 對此答案的評論 -
我以下列方式修改了我的代碼 -
String name = null;
int length = 0;
boolean flag = false;
if(flag) {
name = "abcd";
}
try {
length = name.length();
System.out.println("Number of letters in name: " + length);
} catch(NullPointerException e) {
System.out.println("NullPointerException occured");
}
System.out.println("I am being executed");
現在我不再有警告了。
在這里,正如@Slaw 所建議的,我確保variable
name
有可能不是null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.