java异常之后代码执行测试

时间:2025-02-28 20:36:44

1.程序代码:

    public static void main(String[] args) {

        int[] a = {1,2,3};

        for(int i=0;i<4;i++){
System.out.println(a[i]);
} System.out.println("can execute?");
}

执行结果:
java异常之后代码执行测试

2.程序代码:

public static void main(String[] args) {

        int[] a = {1,2,3};

        try{
for(int i=0;i<4;i++){
System.out.println(a[i]);
}
}catch(Exception e){
e.printStackTrace();
} System.out.println("can execute?");
}

执行结果:

java异常之后代码执行测试

3.程序代码:

    public static void main(String[] args) {

        int[] a = {1,2,3};

        try{
for(int i=0;i<4;i++){
System.out.println(a[i]);
}
}catch(Exception e){
e.printStackTrace();
return;
} System.out.println("can execute?");
}

执行结果:

java异常之后代码执行测试

4.程序代码:

    public static void main(String[] args) throws Exception{

        int[] a = {1,2,3};

        for(int i=0;i<4;i++){
System.out.println(a[i]);
} System.out.println("can execute?");
}

执行结果:
java异常之后代码执行测试

5.程序代码:

public static void main(String[] args) {

        int[] a = {1,2,3};

        try{

            for(int i=0;i<4;i++){
System.out.println(a[i]);
} System.out.println("try can execute?"); }catch(Exception e){
e.printStackTrace();
} System.out.println("can execute?");
}

执行结果:
java异常之后代码执行测试

总结:

  1.如果程序没有对异常进行捕获,当运行到异常时,后面的代码不会执行。(eg:1程序代码)

  2.如果程序对异常进行捕获了,try里面异常后的内容不会执行,try代码块外面的内容会执行(eg:5程序代码)

  3.如果程序对异常进行捕获了,但是catch里面进行了return,try代码外面的内容也不会执行(eg:3程序代码)