java 文件读写操作 异常处理_java - 如何捕获通过读取和写入文件而抛出的所有异常?...

虽然我同意捕获原始异常并不是一种好的方式,但是有一些方法可以处理异常,这些异常提供了卓越的日志记录以及处理意外情况的能力。 由于您处于异常状态,因此您可能对获取良好信息比对响应时间更感兴趣,因此性能的实例不应该是一个大问题。

try{

// IO code

} catch (Exception e){

if(e instanceof IOException){

// handle this exception type

} else if (e instanceof AnotherExceptionType){

//handle this one

} else {

// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.

throw e;

}

}

但是,这并没有考虑到IO也可以抛出错误的事实。 错误不是例外。 错误是与异常不同的继承层次结构,尽管它们共享基类Throwable。 由于IO可以抛出错误,你可能想要抓住Throwable

try{

// IO code

} catch (Throwable t){

if(t instanceof Exception){

if(t instanceof IOException){

// handle this exception type

} else if (t instanceof AnotherExceptionType){

//handle this one

} else {

// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.

}

} else if (t instanceof Error){

if(t instanceof IOError){

// handle this Error

} else if (t instanceof AnotherError){

//handle different Error

} else {

// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.

}

} else {

// This should never be reached, unless you have subclassed Throwable for your own purposes.

throw t;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值