黑马程序员技术交流社区
标题:
想问问有什么好的解决方法
[打印本页]
作者:
fantianfei
时间:
2015-7-10 08:02
标题:
想问问有什么好的解决方法
class NovalueException extends RuntimeException
{
NovalueException(String message)
{
super(message);
}
}
interface Shape
{
void getArea();
}
class Rec implements Shape
{
private double length,width;
Rec(double length, double width)
{
if(length<=0 || width<=0)
throw new NovalueException("出现非法的值");
this.length = length;
this.width = width;
}
public void getArea()
{
System.out.println("Area="+length * width);
}
}
class Cir implements Shape
{
private double radius;
public static final double PI = 3.14;
Cir(double radius)
{
if (radius<=0)
throw new NovalueException("出现非法的值");
this.radius = radius;
}
public void getArea()
{
System.out.println("Area="+radius * radius * PI);
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
Rec r = new Rec(-2.5,3.9);
r.getArea();
Cir c = new Cir(3.0);
c.getArea();
System.out.println("over");
}
}
复制代码
想问我这个程序如果Rec里面出现负值了,下面的Cir就算没有负值,也检测不到,只会直接报出异常终止程序,有什么好的解决方法 两个类之间的执行不会影响到彼此
作者:
半月
时间:
2015-7-10 08:49
你NovalueException继承的是RuntimeException
有异常程序就停止运行了,连try都不用.
改成Exception吧
然后在main中捕获异常处理就可以了
public static void main(String[] args)
{
try{
Rec r=new Rec(-2.5,3.9);
r.getArea();
}catch(NovalueException e){
System.out.println(e);
}
try{
Cir c = new Cir(3.0);
c.getArea();
}catch(NovalueException e){
System.out.println(e);
}
System.out.println("over");
}
复制代码
作者:
fantianfei
时间:
2015-7-10 11:59
半月 发表于 2015-7-10 08:49
你NovalueException继承的是RuntimeException
有异常程序就停止运行了,连try都不用.
改成Exception吧
试了 不行
作者:
fantianfei
时间:
2015-7-10 12:07
半月 发表于 2015-7-10 08:49
你NovalueException继承的是RuntimeException
有异常程序就停止运行了,连try都不用.
改成Exception吧
搞定了,谢谢。。。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2