[英]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.