如何使用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:
}
Run Code Online (Sandbox Code Playgroud)
Try和catch用于优雅地处理异常,而不是隐藏异常.如果你正在调用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();
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,您希望单独捕获异常.盲目捕捉,Exception因为一些答案建议是一个坏主意.你不想抓住你从未见过的东西来处理你所做的事情.如果你想捕获你从未见过的异常,你需要记录它并优雅地向用户显示错误.
| 归档时间: |
|
| 查看次数: |
810 次 |
| 最近记录: |