Try中如果发现错误,即跳出try去匹配catch,那么try后面的语句就不会被执行

例:public void print() throws Exception.

 

对于方法a,如果它定义了throws Exception。那么当它调用的方法b返回异常对象时,方法a并不处理,而将这个异常对象向上一级返回,如果所有的方法均不进行处理,返回到主方法,程序中止。(要避免所有的方法都返回的使用方法,因为这样出现一个很小的异常就会令程序中止)。

 

如果在方法的程序中有一行throw new Exception(),返回错误,那么其后的程序不执行。因为错误返回后,后面的程序肯定没有机会执行,那么JAVA认为以后的程序没有存在的必要。

 

对于try……catch格式:

try  {可能出现错误的代码块}  catch(exception e){进行处理的代码} ;

                               对象变量的声明

 

用这种方法,如果代码正确,那么程序不经过catch语句直接向下运行;

如果代码不正确,则将返回的异常对象和e进行匹配,如果匹配成功,则处理其后面的异常处理代码。(如果用exception来声明e的话,因为exception为所有exception对象的父类,所有肯定匹配成功)。处理完代码后这个例外就完全处理完毕,程序会接着从出现异常的地方向下执行(是从出现异常的地方还是在catch后面呢?利用程序进行验证)。最后程序正常退出。

 

Try中如果发现错误,即跳出try去匹配catch,那么try后面的语句就不会被执行。

 1 package TomText;
 2 //定义一个求圆面积的类。
 3 public class TomText_48 {
 4     private double radius;
 5     final double pi=3.14;
 6     public  double setradius(double r){
 7         return radius=r;
 8     }
 9     
10     public void getRadius() {
11         this.setradius(radius);
12     }
13     public double calculateArea( ) {
14         return pi*radius*radius;
15     }
16     public void res(){
17         System.out.println(this.calculateArea());
18     }
19     public static void main(String[] args){
20         TomText_48 t=new TomText_48();
21         t.setradius(44);
22         double s=t.calculateArea();
23         t.res();
24         System.out.println(s);
25     }
26 
27 }

 

猜你喜欢

转载自www.cnblogs.com/borter/p/9419397.html
今日推荐