|  | 
 
| 
看两份代码:
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 1)
 package practice;
 
 public class Circle {
 
 double radius;
 
 public Circle() {
 this.radius = 1.0;
 }
 
 public Circle(double radius) {
 try {
 setRadius(radius);
 } catch (Exception e) {
 //                        e.printStackTrace();
 System.out.println("SHIT!");
 System.exit(0);
 }
 }
 
 public double getRadius() {
 return radius;
 }
 
 public void setRadius(double radius) throws Exception{  //**
 if (radius < 0)
 throw new Exception("The radius cannot be less than 0!");
 this.radius = radius;
 }
 
 public static void main(String[] args) {
 
 System.out.println("The radius of this circle is "+new Circle().radius);
 System.out.println("The radius of that circle is "+new Circle(5.2).radius);
 System.out.println("The radius of that circle is "+new Circle(-2).radius);
 }
 
 }
 
 2)
 package practice;
 
 public class Pra019 {
 
 public static void main(String[] args) {  //**
 
 try {
 Thread.sleep(1000);
 throw new Exception("Crashed!");
 } catch (Exception e) {
 System.out.println(e.getMessage());
 }
 
 }
 
 }
 -----------------------------------------------------------------------------------
 
 第一份代码,请主要看setRadius那一个方法。
 代码看完了。好,我的问题是:为什么同样是throw一个新的(new)异常,为什么在setRaduis那里必须在方法名后面throws(声明)一下,而在main方法的main名字后面却不需要呢??(为了方便大家看,我们已经把相关的那两行方法代码用注释标出来了。)请踊跃发言,谢谢大家!!
 | 
 |