/*
有一个圆形和长方形,
都可以获取面积,对于面积如果出现非法数值,视为是获取面积出现问题,
问题通过异常来表示,
先要对这个程序进行基本的设计,
*/
//Exception
class NoValueException extends RuntimeException//运行时异常,
{
public 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)
System.out.println("出错了");
else
{
this.len = len;
this.wid = wid;
}
*/
if(len<=0 || wid<=0)//出现问题就跳转
throw new NoValueException("出现非法值");//抛出异常,方法那里要标识一下
this.len = len;
this.wid = wid;
/*
try
{//正常代码:正常时运行的代码,平时看懂程序,看这
this.len = len;
this.wid = wid;
}
catch ()
{//出现问题时,
}
*/
}
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);
}
}
public class ExceptionTest
{
public static void main(String[] args)
{
/* 继承-----Exception-------时
try
{
Rec rec = new Rec(-3, 4);//出问题的放进来
rec.getArea();
}
catch (NoValueException e)
{
System.out.println(e.toString());//显示错误信息
}
*/
Rec rec = new Rec(-3, 4);
rec.getArea();//出现非法值
Circle c = new Circle(-1);
c.getArea();//非法半径
//上面两个只能执行一个
System.out.println("OVER");
}
}