//RuntimeException不处理异常,直接停止程序
class novalueException extends RuntimeException{
novalueException(String message){
super(message);
}
}
interface shape{
void getArea();
}
class rec implements shape{
private int wid,length;
rec(int wid,int length){
if(wid<=0||length<=0)
throw new novalueException(“出现非法值”);
this.length=length;
this.wid= wid;
}
public void getArea(){
System.out.println(wid*length);
}
}
class circle implements shape{
private int radius;
public static final double pi= 3.14;
circle(int radius){
if(radius<=0)
throw new novalueException(“出现非法值”);
this.radius=radius;
}
public void getArea(){
System.out.println(radiusradiuspi);
}
}
class ArrayTool{
public static void main(String[] args) {
rec r = new rec(-3,4);
r.getArea();
circle c = new circle(2);
c.getArea();
}
}
本文介绍了一种通过自定义异常来处理非法输入的方法,并展示了如何在接口设计中使用这种异常处理方式。具体实现了矩形和圆形面积计算的功能,并在构造函数中加入了合法性检查。
2044

被折叠的 条评论
为什么被折叠?



