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

实验源码:

 1 package 实验9;
 2 
 3 public class Shiyan9 {
 4 public static void main(String[] args) {
 5 point p=new point(1,3);
 6 point p1=new point(1,2);
 7 point p2=new point(1,1);
 8 rectangle r=new rectangle(p,5,6);
 9 triangle t=new triangle(p,p1,p2);
10 }
11 
12 }
13 class point {
14 public int x,y;
15 public point() {}
16 public point(int x,int y)throws IllegalArgumentException
17 {
18 this.x=x;
19 this.y=y; 
20 
21 if(x<0||y<0)
22 throw new IllegalArgumentException("参数无效");    
23 }
24 }
25 class rectangle extends point{
26 public int width,length;
27 //public point point1(3,6);
28 public rectangle(point point1,int length,int width)throws IllegalArgumentException
29 {
30 
31 this.length=length;
32 this.width=width;
33 if(length<0||width<0)
34 throw new IllegalArgumentException("参数无效");
35 }
36 } 
37 class triangle extends point{
38 public triangle(point point1,point point2,point point3)throws IllegalArgumentException
39 {
40 if(((point1.x-point2.y)-(point2.x-point1.y))+((point2.x-point3.y)-(point3.x-point2.y))+((point3.x-point1.y)-(point3.y-point1.x))==0)
41 throw new IllegalArgumentException("参数无效");
42 }
43 }

实验结果:

Exception in thread "main" java.lang.IllegalArgumentException: 参数无效
at 实验9.triangle.<init>(Shiyan9.java:42)
at 实验9.Shiyan9.main(Shiyan9.java:10)

 

实验心得:

通过本次实验,了解异常处理机制的必要性和异常处理的措施。

posted @ 2019-05-26 21:07  EvilTime  阅读(389)  评论(0)    收藏  举报