您的位置:首页 > 编程语言 > Java开发

Java基础之异常Exception---测试(带答案)

2016-06-27 16:19 393 查看
ps:案例来源于毕向东老师Java基础教程

题目描述:

有一个圆形和长方形。

都可以获取面积。对于面积如果出现非法的数值,视为是获取面积出现问题。

问题通过异常来表示。

现有对这个程序进行基本设计。

实例代码:

class NoValueException extends RuntimeException
{
NoValueException(String message)
{
super(message);
}
}

interface Shape
{
void getArea();
}

class Rec implements Shape
{
private int len,wid;

Rec(int len ,int wid)//throws NoValueException
{
if(len<=0 || wid<=0)
throw new NoValueException("出现非法值");

this.len = len;
this.wid = wid;
}

public void getArea()
{
System.out.println(len*wid);
}
}

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

class  ExceptionTest1
{
public static void main(String[] args)
{

Rec r = new Rec(3,4);
r.getArea();

Circle c = new Circle(-8);

System.out.println("over");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 异常