java 捕获异常顺序_在Java中捕获异常的顺序

该顺序是任何匹配的第一,被执行(

as the JLS clearly explains)。

如果第一个catch匹配异常,它会执行,如果没有,则下一个被尝试并且被打开,直到一个匹配或没有。

所以,当捕获异常时,你总是能够捕获最特定的第一个,然后是最通用的(如RuntimeException或者Exception)。例如,假设您想要捕获String.charAt(index)方法抛出的StringIndexOutOfBoundsException,但您的代码也可能会抛出NullPointerException,以下是如何捕获异常:

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();

}

所以,通过这个顺序,我确保异常被正确捕获,并且它们不会彼此跳过,如果它是一个NullPointerException,它进入第一个catch,如果一个StringIndexOutOfBoundsException它进入第二个,最后如果它是别的东西一个RuntimeException(或从它继承,像一个IllegalArgumentException)它进入第三个catch。

您的情况是正确的,因为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();

}

所以,你应该先让孩子,然后父母的例外。

该顺序是任何匹配的第一,被执行( as the JLS clearly explains)。 如果第一个catch匹配异常,它会执行,如果没有,则下一个被尝试并且被打开,直到一个匹配或没有。 所以,当捕获异常时,你总是能够捕获最特定的第一个,然后是最通用的(如RuntimeException或者Exception)。例如,假设您想要捕获String.charAt(index)方法抛出的StringIndexOutOfBoundsException,但您的代码也可能会抛出NullPointerException,以下是如何捕获异常: 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(); } 所以,通过这个顺序,我确保异常被正确捕获,并且它们不会彼此跳过,如果它是一个NullPointerException,它进入第一个catch,如果一个StringIndexOutOfBoundsException它进入第二个,最后如果它是别的东西一个RuntimeException(或从它继承,像一个IllegalArgumentException)它进入第三个catch。 您的情况是正确的,因为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(); } 所以,你应该先让孩子,然后父母的例外。
经验分享 程序员 微信小程序 职场和发展