以下代码段...
try
{
myFile = new FileInputStream( "something.dat" );
...
}
catch ( IOExcpetion ioe )
{
...
}
finally
{
try
{
myFile.close();
}
catch ( Exception e )
{
...
}
}
...据我了解,最终是在关闭文件。但是,为什么必须在其中包含另一个try / catch块呢?对我来说似乎很尴尬。有没有解决的办法?
在close()
上调用方法FIleInputStream
必须由try catch
子句包围。API方法本身抛出IOException异常。此外IOException异常是经过检查的异常,所以我们需要处理这个问题。
检查异常
被检查的异常在编译时被检查。这意味着如果一个方法抛出一个检查过的异常,那么它应该使用try-catch块处理该异常,或者应该使用throws关键字声明该异常,否则程序将给出编译错误。因为这些异常是在编译时检查的,所以将其命名为“已检查的异常”。
通过API,
/**
* Closes this file input stream and releases any system resources
* associated with the stream.
*
* <p> If this stream has an associated channel then the channel is closed
* as well.
*
* @exception IOException if an I/O error occurs.
*
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
}
由于close()
,方法正在抛出IOException
,因此您需要re-throw the same
在语句周围加上或try/catch
。
推荐这个
还谈到Java7,您可以方便地处理相同的内容
1.)捕获多个异常
要了解IOException的原因,请在此处参考类似的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句