java中的try-and-catch语句?
如何使用try和catch语句而不是方法标头中的throws子句重写以下方法:java中的try-and-catch语句?,java,exception-handling,Java,Exception Handling,如何使用try和catch语句而不是方法标头中的throws子句重写以下方法: public String getInput(String filename) throws Exception { BufferedReader infile = new BufferedReader (new FileReader(filename)); String response = infile.readLine(); infile.close(); return res
public String getInput(String filename) throws Exception
{
BufferedReader infile = new BufferedReader (new FileReader(filename));
String response = infile.readLine();
infile.close();
return response:
}
像这样的东西应该可以做到:
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
未正确关闭,则可能会导致memleaks。Try-and-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();
}
值得注意的是,您希望单独捕获异常。正如一些答案所暗示的那样,盲目捕捉异常是个坏主意。你不想抓住你从未见过的事情来处理你所做的事情。如果您想捕获从未出现过的异常,则需要将其记录下来,并优雅地向用户显示错误。以下是一个关于异常处理策略的好方法: 还有一些其他想法:
至于代码,请查看@Pablo Santa Cruz's并阅读评论。我的代码会非常相似。我会这样写:
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;
}
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();
}
}
在这种特殊情况下,如果抛出异常,则空字符串
“
对我很好。情况并非总是如此 这是对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 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;
}
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作为包装,我们可以定义我们自己的异常类型)除了NPE-再次尝试两个try语句。还应使用字符串而不是字符串。:-)不捕获异常。。。捕获IOException(请参阅我对Pablo Santa Cruz的评论)。潜在的NPE执行
infle.close()
(例如,未找到文件)永远不会捕获异常,除非您必须这样做。任何引发异常的通用API都已损坏。您应该执行catch(IOE异常)。而且此代码是错误的。。。您必须将关闭放在finally块中,否则如果readLine抛出异常,它将无法关闭(具体取决于操作系统中文件句柄的实现方式)。@Tofu-同意。任何API都不应该抛出或捕获异常,但这正是发布问题的人所要求的。给出错误建议没有任何借口:-)(但至少我看到了你的动机)。也有轻微的调整…“infle.close()”不会按照编写的方式编译,因为BufferedReader是在“try”块中声明的,而不是在方法级别声明的。我也同意@TofuBeer…将catch更改为IOException not Exception.close-只需捕获最后一个IOException
就完成了最完整的答案。仅在finally块中缺少IOException的捕获。不要声明方法引发异常。。。尽量说得具体些。在这种情况下,IOException。如果这是标记为“家庭作业”,我想知道这是否意味着他的老师实际上用“抛出异常”来写原始问题。这是一个更可怕的前景,嗯-有一天我让一个学生向我求助。。。我花了一个小时来清理由于异常而导致的抛出/尝试/捕获。我提醒他们不应该那样做。。。他们说这门课的老师,他们现在告诉他们去做。。。叹气我正在修复的问题也是由于捕获异常造成的。。。所以至少我向学生证明了我的观点:-)我更喜欢null
以上的“
。这在更高级别上更容易处理。1)打印IOException的StackTrace,它(几乎)总是有用的。。。。。2) 空的catch不是一个很好的例子,它可以隐藏重要的错误。如果存在以前的错误,那么在关闭读卡器时发生错误时,您将隐藏它。如果error
变量不为空,我不会更改它。@Carlos,是的,我知道并考虑过它,但后来我决定在这方面保持简单。通常,FileContent应该包含一组错误。只有一种可能,错误被隐藏了:那就是当我们在关闭流时发生了一个异常并得到另一个异常。这是非常,非常不可能的,这就是为什么实施它的“捷径”。