Pat*_*ck 0 java eclipse exception try-catch-finally bufferedreader
这是我的代码:
public static String readFile()
{
BufferedReader br = null;
String line;
String dump="";
try
{
br = new BufferedReader(new FileReader("dbDumpTest.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
System.exit(0);
}
try
{
while( (line = br.readLine()) != null)
{
dump += line + "\r\n";
}
}
catch (IOException e)
{
System.out.println(e.getMessage() + " Error reading file");
}
finally
{
br.close();
}
return dump;
Run Code Online (Sandbox Code Playgroud)
因此eclipse正在抱怨由此引发的未处理的IO异常 br.close();
为什么会导致IO异常?
我的第二个问题是为什么eclipse不会抱怨以下代码:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// releases any system resources associated with reader
br.close();
// creates error
br.read();
}catch(IOException e){
// IO error
System.out.println("The buffered reader is closed");
}finally{
// releases any system resources associated
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你能按照Laymen的说法保留解释,我会很感激.我在这里先向您的帮助表示感谢
这两个代码示例都应该有编译错误抱怨未处理的IOException.Eclipse在我的两个代码示例中都将这些显示为错误.
原因是该close方法IOException在finally块中调用时抛出一个已检查的异常,该块位于try块之外.
修复是使用try-with-resources语句,该语句在Java 1.7+中可用.声明的资源是隐式关闭的.
try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
// Your br processing code here
}
catch (IOException e)
{
// Your handling code here
}
// no finally necessary.
Run Code Online (Sandbox Code Playgroud)
在Java 1.7之前,您需要将调用包装在close()块内的try-catch块中finally.这是一个冗长的代码,以确保一切都关闭和清理.
finally
{
try{ if (is != null) is.close(); } catch (IOException ignored) {}
try{ if (isr != null) isr.close(); } catch (IOException ignored) {}
try{ if (br != null) br.close(); } catch (IOException ignored) {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |