首页 > 技术文章 > catch 里面的代码和try catch 外面的代码执行顺序很奇怪,求大神指点

jjunior 2020-04-19 21:44 原文

 1 package multiShape;
 2 
 3 public class People {
 4     public String className = "people class";
 5     public void eat() {
 6         System.out.println("People eat");
 7     }
 8     
 9     public void breath() {
10         System.out.println("People breath");
11     }
12 
13 }
 1 package multiShape;
 2 
 3 public class Student extends People{
 4     public String className = "Student class";
 5     
 6     public void eat() {
 7         System.out.println("Student eat");
 8     }
 9     
10     public void study() {
11         System.out.println("Student study");
12     }
13 }

 

 1 package multiShape;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         People pp = new Student();
 8         pp.breath();
 9         pp.eat();
10         System.out.println("---" + pp.className);
11         try {
12         if(1 > 0) {throw new IllegalArgumentException("throw my exception");}
13         }
14         catch(Exception e) {
15             e.printStackTrace();
16             System.out.println("======================" );
17         }
18         Student st = (Student)pp;
19         st.breath();
20         st.eat();
21         st.study();
22         System.out.println("---" + st.className);
23     }
24 }

 

main 方法的执行结果:

People breath
Student eat
java.lang.IllegalArgumentException: throw my exception
---people class
======================
People breath
Student eat
Student study
---Student class
at multiShape.Test.main(Test.java:12)

 

感觉上面的这个执行结果的输出的顺序很奇怪,和我预期的结果有点不一样,我预期的结果应该是像下面这样子的:

 

People breath
Student eat
---people class
java.lang.IllegalArgumentException: throw my exception
at multiShape.Test.main(Test.java:12)
======================
People breath
Student eat
Student study
---Student class

请问为什么执行结果会是那样,而且每次执行后的输出结果顺序都会有不一样 , 是不是因为catch 里面的代码和main 函数里面的代码是由两个线程来执行的。请大神指点。

推荐阅读