JAVA异常

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());
		}
}

运行结果


我在操作的时候没有自定义异常类,如果想要让这个异常看起来更详细些,就可以再新建自定义类继承


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值