try catch嵌套执行顺序

直接上例子:
import org.junit.Test;

public class ExceptionTest {
@Test
public void testTryCatch() {
try {
System.out.println(“A”);
//Integer.parseInt(null);
try {
System.out.println(“B”);
// Integer.parseInt(null);
} catch (Exception ex2) {
System.out.println(“C”);
//Integer.parseInt(null);
} finally {
System.out.println(" D “);
// Integer.parseInt(null);
}
System.out.println(” E ");
// Integer.parseInt(null);
} catch (Exception ex) {
try {
System.out.println("F ");
// Integer.parseInt(null);
} catch (Exception ex2) {
System.out.println("G ");
// Integer.parseInt(null);
} finally {
System.out.println("H ");
//Integer.parseInt(null);
}
System.out.println("I ");
//Integer.parseInt(null);
} finally {
System.out.println("J ");
Integer.parseInt(null);
}
}
}

运行结果:

A抛异常:
A-F-H-I-J

B抛异常:
A-B-C-D-E-J

C抛异常:
A-B-D-E-J

D抛异常:
A-B-D-F-H-I-J

E抛异常:

A-B-D-E-F-H-I-J

F抛异常:
A-B-D-E-J

G抛异常:
A-B-D-E-J

H抛异常:
A-B-D-E-J

I抛异常:
A-B-D-E-J

J抛异常:
A-B-D-E-J

总结:
finally:
①同级有没有异常都执行;
②父级有异常,子类finally不执行

catch里有异常,不会产生任何影响,因为程序根本不走catch里的代码,也不会执行父类的catch。

父try有异常,子类的try,catch,finally和父try后代码不会执行;
子类try有异常,子catch能捕获,走子catch,否则走父catch。

你可能感兴趣的:(try catch嵌套执行顺序)