如果你編寫一個包含try-catch塊的非主方法,並且以後在另一個方法中,你想調用該方法,那麼過程是什麼?我無法弄清楚。對調用包含'try-catch'塊的方法感到困惑
我自己的情況如下:
對於一個簡單的Java「迷宮遊戲」,我寫了稱爲靜態無效的方法「祕技(字符串mazeGameSave)拋出IO異常」。這個方法包含一個'try'塊,在這個塊中,我寫了將所有'board'(作爲二維數組)打印到一個新文件所需的所有代碼,然後是一個簡短的'catch'塊,在那裏我打印出一個錯誤消息(您可以在下面看到相同的消息)。
很明顯,我想在另一個靜態無效方法中調用這個方法,這個方法用於處理其他方法,如用戶輸入所指定的那樣,而且我完全按照您在下面看到的那樣執行了這個操作,其中String「action」是包含此塊的靜態void方法的參數。
if (action.charAt(0) == ('S' | 's')
&& action.charAt(1) == ('a' | 'A')
&& action.charAt(2) == ('v' | 'V')
&& action.charAt(3) == ('e' | 'E')
&& action.charAt(4) == ' ') {
String [] parts = action.split(" ");
String saveCommand = parts[0];
String fileName = parts[1];
try {
saveGame(fileName);
} catch (IOException e) {
System.err.printf("Error: Could not save the current game configuration to \'%s\'. \n", fileName);
}
}
下面我提意見的建議,這裏是遊戲存檔()代碼:
public static void saveGame (String mazeGameSave) throws IOException {
File save = new File(mazeGameSave);
try {
PrintWriter output = new PrintWriter("mazeGameSave");
output.printf(lives + " " + steps + " " + gold + " " + boardRows + "\n");
for (int j = 0; j < boardRows; j ++) {
for (int k = 0; k < columns; k ++) {
output.print(board[j][k]);
}
output.print("\n");
}
output.close();
output.printf("Successfully saved the current game configuration to \'%s\'.", mazeGameSave);
}
catch (IOException e) {
System.err.printf("Error: Could not save the current game configuration to \'%s\'.", mazeGameSave);
return;
}}
所以這個關鍵愚蠢的方面是,我已經寫了一模一樣的‘在catch’塊performAction(action)方法,就像我在我的原始saveGame(...)方法中所做的那樣。這不起作用...那麼,我該怎麼辦?
什麼問題?你想在saveGame()和performAction()中執行你的catch塊嗎? – sovas
不,我只是從字面上不知道如何調用方法saveGame(...)以一種方式工作... –
@NoamHudson正在生成的錯誤處理在2級。而已。調用'saveGame()'方法時面臨什麼問題? –