如果我没记错的话,应该首先捕获异常的子类。但是必须捕获任何 RuntimeException 和一个具体的检查异常,这应该首先捕获?
try {
...
} catch(RuntimeException e) {
...
} catch(IOException e) {
...
}
这个顺序正确吗?或者它是正确的但却是一个糟糕的选择?
顺序是无论先匹配什么,都会被执行 (正如 JLS 明确解释的那样).
如果第一个 catch 与异常匹配,则执行,如果不匹配,则尝试下一个 catch,直到有一个匹配或没有匹配为止。
因此,当捕获异常时,您希望始终捕获最具体的首先是最通用的(如 RuntimeException 或 Exception)。例如,假设您想赶上StringIndexOutOfBoundsException抛出的String.charAt(索引)方法,但你的代码也可能会抛出空指针异常,以下是捕获异常的方法:
String s = null;
try {
s.charAt(10);
} catch ( NullPointerExeption e ) {
System.out.println("null");
e.printStackTrace();
} catch ( StringIndexOutOfBoundsException e ) {
System.out.println("String index error!");
e.printStackTrace();
} catch ( RuntimeException e ) {
System.out.println("runtime exception!");
e.printStackTrace();
}
因此,通过这个命令,我确保正确捕获异常,并且如果它是一个异常,它们不会互相绊倒。空指针异常它进入第一个捕获,如果StringIndexOutOfBoundsException它进入第二个,最后如果它是一个 RuntimeException 的其他东西(或者继承自它,就像一个非法参数异常)它进入第三个捕获。
您的情况是正确的,因为 IOException 继承自 Exception ,而 RuntimeException 也继承自 Exception ,因此它们不会相互绊倒。
首先捕获通用异常然后再捕获它的后代之一也是一个编译错误,如下所示:
try {
// some code here
} catch ( Exception e) {
e.printStackTrace();
} catch ( RuntimeException e ) { // this line will cause a compilation error because it would never be executed since the first catch would pick the exception
e.printStackTrace();
}
所以,你应该先有孩子,然后才是父母例外。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)