这java found at,同时捕获java异常FileNotFound和IOException

Is the FileNotFoundException somehow a "sub-exception" of the IOException?

This is my code opening an input stream to a file at the given path:

method(){

FileInputStream fs;

try {

fs = new FileInputStream(path);

//

fs.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

How come I can neglect the FileNotFound and just catch the IOException instead?

Is the FNFException a part of the IOException?

Instead of catching the exceptions, what if I throw an IOException in my method?

method() throws IOException{

FileInputStream fs;

fs = new FileInputStream(path);

//

fs.close();

}

Can I proceed to catch a FileNotFoundException at the invoking method like this?

try {

method();

}catch (FileNotFoundException e1) {}

Thanks for any help you might be able to provide!

解决方案

Is the FileNotFoundException somehow a "sub-exception" of the IOException?

Yes, FileNotFoundException extends IOException:

java.lang.Object

java.lang.Throwable

java.lang.Exception

java.io.IOException

java.io.FileNotFoundException

How come I can neglect the FileNotFound and just catch the IOException instead?

Catching a base class of the exception being thrown will catch the exception, unless there is a more specific catch clause available.

Can I proceed to catch a FileNotFoundException at the invoking method like this?

Absolutely! In fact, this is a good thing to do: your code should handle only the exceptions with which it knows how to deal, and let all other exceptions propagate to a place where it could be dealt with in a better way.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值