我正在java中实现异常处理,有多个异常。
查看以下场景:函数f1抛出异常e1、e2、e3和e4,而函数f2捕获这些异常。
现在我想要捕获e1,e2显式地通过catch (异常e1和e2)捕获,其他的异常应该通过catch(异常e)在同一个块中全部捕获,因此e1和e2是一个特例,其他都是一般的异常。
那么接下来的工作呢?
try{
//some work`
} catch(ExceptionType1 e1) {
//do some special logging
} catch (ExceptionType2 e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}我的问题是,ExceptionType1(e1)是否也会被e例外所捕获?
发布于 2014-03-11 23:54:06
规格写入
如果由于值V的抛出而突然完成try块的执行,则有一个选择:
- If that block completes normally, then the try statement completes normally.
- If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
因此,最多只执行一个catch块。
发布于 2014-03-11 23:47:30
为此,需要有具有不同异常(如NullPointerException NumberFormatException )的捕获块,而带有异常参数的catch块将捕获一般异常,因为异常是所有异常的超类。
try{
//some work`
} catch(NullPointerException e1) {
//do some special logging
} catch (NumberFormatException e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}发布于 2014-03-11 23:48:47
使用代码将捕获catch(Exception e1){...}中的所有异常
另一个catch-blocks未使用。如果您想以不同的方式处理不同的Exception-types,则必须给catch(...)其他Exception-types。
喜欢
try{
}catch(IOException e1){
// Do sth
}
catch(NullPointerException e2){
// Do sth else
}
// and so on...https://stackoverflow.com/questions/22339052
复制相似问题