[英]try and catch statements in java?
我如何使用try和catch語句而不是方法標題中的throws子句重寫以下方法:
public String getInput(String filename) throws Exception
{
BufferedReader infile = new BufferedReader (new FileReader(filename));
String response = infile.readLine();
infile.close();
return response:
}
嘗試和捕獲用於優雅地處理異常,而不是隱藏它們。 如果您正在調用getinput(),您是否想知道是否出了問題? 如果您想隱藏它,我想您可以做些類似的事情
public String getInput(String file) {
StringBuilder ret = new StringBuilder();
String buf;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader(filename));
while (buf = inFile.readLine())
ret.append(buf);
} catch (FileNotFoundException e) {
ret.append("Couldn't find " + file);
} catch (IOException e) {
ret.append("There was an error reading the file.");
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (IOException aargh) {
// TODO do something (or nothing)
}
}
}
return ret.toString();
}
值得注意的是,您想單獨捕獲異常。 正如一些答案所建議的那樣,盲目地捕獲Exception
是一個壞主意。 您不想捕捉從未見過的事情來處理您所做的事情。 如果您想捕獲異常,而您從未見過,則需要對其進行記錄並向用戶優雅地顯示錯誤。
這是一個關於異常處理策略的優秀SO線程:
還有一些其他想法:
注意捕捉並隱藏它們。 在這種情況下,我想說的是使用“ throws”實際上更好,因為您是在向方法的調用者通知發生了問題,並且您無法跟上討價還價(返回有效的響應)。 盡管我會說“引發IOException”,而不只是普通的“ Exception”。 如果您要麻煩捕獲異常,請對其進行一些建設性的操作,不要僅僅為了捕獲它而捕獲它。
在處理文件I / O時,可能需要使用try / catch / finally,並在finally子句中關閉文件。
就代碼而言,請查看@Pablo Santa Cruz並閱讀注釋。 我的代碼將非常相似。
public String getInput(String filename)
{
BufferedReader infile = null;
try {
infile = new BufferedReader (new FileReader(filename));
String response = infile.readLine();
return response;
} catch (IOException e) {
// handle exception here
} finally {
try { infile.close(); } catch (IOException e) { }
}
return null;
}
這樣的事情應該做到:
public String getinput(String filename)
{
BufferedReader infile = null;
String response = null;
try {
infile = new BufferedReader(new FileReader(filename));
response = infile.readLine();
} catch (IOException e) {
//handle exception
} finally {
try {
if (infile != null)
infile.close();
} catch (IOException e) {
//handle exception
}
}
return response;
}
請注意,您應該添加其他人聲明的finally
子句,因為如果由於異常而導致BufferedReader
未正確關閉,則可能會導致記憶泄漏。
我會這樣寫:
public String getInput(String filename) {
BufferedReader infile = null;
String response = "";
try {
infile = new BufferedReader (new FileReader(filename));
response = infile.readLine();
} catch( IOException ioe ) {
System.err.printf("Exception trying to read: %s. IOException.getMessage(): %s",
filename, ioe.getMessage() );
} finally {
if( infile != null ) try {
infile.close();
} catch( IOException ioe ){}
}
return response;
}
在這種特殊情況下,如果引發異常,則空字符串""
對我有好處。 這並非總是如此。
這是jcms答案的改編-這樣做是因為我不喜歡他的解決方案中的異常處理...
如果發生異常,我們必須決定要怎么做。 通常在某些要求中涵蓋了這一點。 記錄是一個好主意,但我們仍然必須做一些事情。 至少我永遠不會使用返回值來報告文件內容以及錯誤消息。 對於接收器而言,這很難解碼。 如果文件丟失或IO錯誤是一種例外情況,則可能會引發異常-通常的方式。 或者,這就是我的建議,我們定義一個小類以返回文件內容和錯誤狀態:
public class FileContent {
private String fileContent = null;
private Throwable error = null;
public FileContent(String fileContent, Throwable error) {
this.error = error;
this.fileContent = fileContent;
}
// getters for all fields (no setters!)
public boolean isValid() {
return (error == null);
}
}
而getInput()
方法將如下所示:
public FileContent getInput(final String fileName) {
final StringBuilder fileContentBuilder = new StringBuilder();
String buffer = null;
BufferedReader reader = null;
Throwable error = null;
try {
reader = new BufferedReader(new FileReader(fileName));
while (buffer = reader.readLine()) {
fileContentBuilder.append(buffer);
}
} catch (FileNotFoundException e) {
error = new RuntimeException("Couldn't find " + fileName, e);
} catch (IOException e) {
error = new RuntimeException("There was an error reading the file.", e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (IOException e) {
error = new RuntimeException(
"Couldn't close reader for file " + fileName, e);
}
}
}
return new FileContent(fileContentBuilder.toString(), error);
}
public void useGetInput() {
FileContent content = getInput("your/path/to/your/file");
if (content.isValid()) {
System.out.println(content.getFileContent());
} else {
content.getError().printStackTrace();
}
}
(改進;我們可以定義自己的異常類型,而不是使用RuntimeException作為包裝器)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.