[英]How to catch the exception caused by an absence of an object in Java?
我有一個非常簡單的方法:
public int getScore() {
return game.gameWindow.userBestScore;
}
問題是game
對象或gameWindow
不存在會發生。 我不想得到Null Pointer Exception。 怎么能以正確的方式捕獲它? 我可以這樣做嗎:
public int getScore() {
try{
return game.gameWindow.userBestScore;
} catch(NullPointerException e){
return -1;
}
}
不要捕獲NullPointerException
。
NullPointerException
表示您的代碼不遵守某些合同。 如果game
可能為null
,那么您需要進行明確的測試:
if(game != null) {
...
}
else {
...
}
如果game
不應為null,那么可以使用assert
確保代碼的正確性。
assert game != null;
...
更令人擔憂的是, game
似乎是你班級的私人成員。 在這種情況下, game
可能不應該為null
(盡管有可能發生這種情況)。 你在構造函數中正確初始化它嗎? 我要說的是,你要做的第一件事就是確保正確地初始化game
。 否則,您的代碼最終會被不必要的null
檢查所困擾。 例如,如果Game
類中的gameWindow
沒有正確初始化怎么辦? 你需要另外一個null
-check:
if(game !== null && game.gameWindow != null) {
...
}
else {
...
}
因此,您應首先確保正確初始化對象的私有成員。 如果它們是,並且事實證明game
有一個有效的用例為null
,那么你需要一個明確的null-
檢查。 測試null
總是比捕獲NullPointerException
更好。 除了不應該使用異常來控制業務邏輯流的事實之外,如果在鏈的某個地方生成了有效的NullPointerException
(由於編程錯誤),該怎么辦? 現在你的catch
會捕獲它,你不會知道它; 這可能導致一些非常討厭和難以發現的錯誤。
你可以做到這一點。 在嘗試訪問userBestScore之前,您還可以檢查game和gameWindow是否為null。
if(game != null && game.gameWindow != null)
return game.gameWindow.userBestScore
檢查變量是否為null
,如下所示:
public int getScore() {
if(game == null || game.gameWindow == null){
return -1;
}
return game.gameWindow.userBestScore;
}
public int getScore() {
return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore);
}
你可以做到這一點。 或者,您可以在取消引用這些對象之前檢查null,並在不拋出異常的情況下采取適當的操作。 那會更有效率。
你應該問的真正問題是:為什么一個對象對私有數據成員有空引用? 您沒有正確構建對象。 應該正確初始化對象,並在創建后100%准備好。 否則,您最終必須在代碼中不必要地采取防御措施。
避免盡可能多地拋出異常。 處理已知問題比拋出異常更好。
在某些地方你必須進行空檢查。 可能在調用getScore()方法之前,因為如果游戲或gameWindow為null,則無法調用該方法。
if (game != null && gameWindow != null)
{
int score = getScore();
}
要么
public int getScore()
{
if (game != null && gameWindow != null)
{
return game.gameWindow.userBestScore;
}
else
{
return -1;
}
}
不要做重復的空檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.