JAVA异常中 Exception 的运行异常处理
任务
有一个圆形和长方形, 都可以获取面积。
对于面积如果出现非法的数值,视为是获取面积出现问题,问题通过异常来表示。对这个程序进行基础设计。
基本思路:
首先分析这个题目的共同特点,是可以获取面积,那么可以先定义一个获取面积的接口
public interface IArea {
void getArea();
}
圆和长方形实现这个接口,并且属性私有化。
两个构造方法,有参和无参,在有参构造方法中抛出异常
定义属性的set 和 get方法
长方形:
public class Rect implements IArea {
private int width;
private int heigth;
public Rect() {
super();
// TODO Auto-generated constructor stub
}
//在有参构造方法中抛出异常
public Rect(int width, int heigth) throws Exception {
super();
if (width <= 0||heigth<=0) {
throw new Exception();
}
this.width = width;
this.heigth = heigth;
}
@Override
public void getArea(){
System.out.println("长方形的面积:"+width*heigth);
}
public int getWidth(){
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeigth() {
return heigth;
}
public void setHeigth(int heigth) {
this.heigth = heigth;
}
}
圆形:
在圆形中的π要把它定义成常数
public class Circle implements IArea {
private int radius; //私有化属性
public static final double PI = 3.14; //定义成常数
public Circle(){
super();
}
public Circle(int radius) throws Exception{
super();
//如果半径非法,就抛出去
if (radius<=0) {
throw new Exception();
}
this.radius = radius;
}
@Override
public void getArea(){
//计算面积
System.out.println("圆形面积:"+PI*radius*radius);
}
public int getRadius(){
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
在主方法里面去try ```` catch``````并调用方法
public static void main(String[] args)
{
try { //抓异常
Circle cir = new Circle(4); //传入参数
cir.getArea();
Rect rect = new Rect(-2,5);
rect.getArea();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
运行结果
我在操作的时候没有自定义异常类,如果想要让这个异常看起来更详细些,就可以再新建自定义类继承