黑马程序员技术交流社区
标题:
面向对象之异常应用实例
[打印本页]
作者:
边情2015
时间:
2015-10-1 20:36
标题:
面向对象之异常应用实例
有一个长方形和圆形,获取面积时,对于面积如果出现非法数值时,视为获取面积出现错误。问题通过异常来表示。
class NoValueException extends RuntimeException
{
NoValueException(String msg)
{
super(msg);
}
}
interface Shape
{
public abstract double getArea();
}
class Rec implements Shape
{
private double a,b;
Rec(double a,double b) throws NoValueException
{
if(a<=0 || b<=0)
throw new NoValueException("出错了");
this.a = a;
this.b = b;
}
public double getArea()
{
return a*b;
}
}
class Cir implements Shape
{
private double r;
private static final double pi=3.14;
Cir(double r)
{
if(r<=0)
throw new NoValueException("出错了");//NoValueException 继承了RuntimeException,在这里不用抛出
this.r = r;
}
public double getArea()
{
return r*r*pi;
}
}
class ExceptionTest1
{
public static void main(String[] args)
{
try
{
Rec ab = new Rec(-3,4);
System.out.println(ab.getArea());
}
catch (NoValueException e)
{
System.out.println(e.toString());
}
System.out.println("Get Rec area over");//抛出的异常有try_catch掉 所以程序继续执行后面的语句
Cir c = new Cir(-2.5);
System.out.println(c.getArea());//由于抛出的异常为RuntimeException类开 因此程序执行到这里会停止,等待改证。(异常出现没法运算,这种情况就是RuntimeException类型)
System.out.println("Cir Rec area over");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2