一个catch块中有多种不同类型的异常处理?

Del*_*lta 12 java

如果catch()中允许多个异常,那么它将减少冗余错误处理代码的数量.例如,

try{
// some statments 
}
catch(Type1Exception t1, Type2Exception t2, Type3Exception t3) {   // wish if this could be allowed
/* t1, t2, t3 are children of Exception and needs same error handling then why to have different catch blocks with same piece of code */
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 18

是的 - 这就是Java 7支持它的原因.

所以你的例子实际上是:

try {
} catch (Type1Exception | Type2Exception | Type3Exception ex) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

  • @ Eng.Fouad:不,他的意思是`|`.:-)教程说:"在catch子句中,指定块可以处理的异常类型,并用垂直条(|)分隔每个异常类型" (2认同)