实验九:异常的抛出、捕获并处理
一、源代码
package err;
public class err {
public static void main(String[] args) throws IllegalArgumentException
{ Point point1=new Point (25,1);
Point point2=new Point (46,2);
Point point3=new Point (9,3);
new Rectangle(point1, 12,3);
new Triangle(point1,point2,point3);
Point[] point= {point1,point2};
new Polygon(point);
}
}
class Point
{ public Point() {};
public int x;
public int y;
public Point(int x,int y)
{ this.x=x;
this.y=y;
if(x<0||y<0)
throw new IllegalArgumentException("Point中无效参数异常");
}
}
class Rectangle extends Point
{
public int length,width;
public Rectangle(Point point1,int length,int width) {
this.length=length;
this.width=width;
if(length<0||width<0)
throw new IllegalArgumentException("Rectangle无效参数异常");
}
}
class Triangle extends Point
{
public Triangle(Point point1,Point point2,Point point3) {
if(point1.x/point1.y==point2.x/point2.y&&point2.x/point2.y==point3.x/point3.y)
throw new IllegalArgumentException("Triangle无效参数异常");
}
}
class Polygon extends Point
{ int i=0;
public Polygon(Point[] points)
{ i=points.length;
if(i<=2)
throw new IllegalArgumentException("Polygon无效参数异常");
}
}
二、结果
三、心得
1、Java中的所有异常都是由Throwable类的子类生成的对象,所有的异常类都是Throwable类的子类或子类的子类。Throwable类是Object类的直接子类,Error类和Exception类是Throwable类的两个直接子类。
2、throw 异常对象
3、抛出异常可以直接在主函数中抛出,也可以在类中直接抛出