实验九:异常的抛出、捕获并处理

时间:2021-06-29 18:24:48

一.程序代码

package error;

public class Throwerror {

public static void main(String[] args) throws IllegalArgumentException

{ Point point1=new Point (3,1);

          Point point2=new Point (6,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无效参数异常");

}

二.心得体会

        通过本次实验,我基本了解到了java语言中独特的异常处理机制,

并且学会了异常处理方法以及正确的使用捕获异常和声明抛弃异常的两

种异常处理的方法,此外我还了解到自定义异常类的使用抛出异常和声

明抛出异常的区别与联系。