class AreaFuException extends RuntimeException
{
AreaFuException(){
super();
}
AreaFuException(String message){
super(message);
}
}
class Rectangle
{
private double width;
private double length;
Rectangle(){
super();
}
Rectangle(double width,double length){
if(width<0||length<0)
throw new AreaFuException("面积为负数了"); //创建了运行时异常,编译时无异常运行时才有异常,将异常抛给Java虚拟机处理。无需抛出或try catch处理。
this.width=width; //发生运行时异常时默认调用printStackTrace()方法
this.length=length;
}
public double area(){
return length*width;
}
}
class Demo2
{
public static void main(String[] args)
{
//计算长方形面积,用面向对象的思想实现
//自定义 面积为负数异常(面积为负数看成异常)
Rectangle r = new Rectangle(5,-8);
System.out.println(r.area());
}
}