【Java:异常处理遇到的问题。】
看两份代码: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名字后面却不需要呢??(为了方便大家看,我们已经把相关的那两行方法代码用注释标出来了。)请踊跃发言,谢谢大家!! 你不是调用setRadius()这个函数时候捕捉了吗,所以给捉住了就不用再往外扔了 你不是调用setRadius()这个函数时候捕捉了吗,所以给捉住了就不用再往外扔了 你说的是在构造方法中catch捕捉吧
页:
[1]