在 uni-catch 子句中,您可以自由地重新分配异常对象。例如,这很好用:
try {
... // code that can throw IOException or some user-defined ParserException
} catch(IOException) {
e = new IOException(); // this is acceptable (although there is no point in doing it)
e.printStackTrace();
}
编译器肯定知道抛出的对象是 type IOException
。但是,在 multi-catch 子句中,您可以使用以下内容:
try {
... // code that can throw IOException or some user-defined ParserException
} catch(IOException | ParserException e) {
e = new IOException(); // this is NOT acceptable -- e may reference a ParserException
e.printStackTrace();
}
在这种情况下,编译器在编译时不知道异常是哪种类型,因此将 new 分配给IOException
可以引用an或IOException
不ParseException
应该允许的变量。除此之外,首先缺乏分配给异常变量的用例。final
因此,隐式生成变量并避免所有这些混淆是非常有意义的。如果你真的需要给变量赋值,你可以切换到写catch
块序列的旧方式。