异常的抛出,捕获并处理
Posted java-17
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异常的抛出,捕获并处理相关的知识,希望对你有一定的参考价值。
源程序:
public class dong {
public static void main(String[] args) {
point p=new point(-1,3);
point p1=new point(4,2);
point p2=new point(3,3);
rectangle r=new rectangle(p,2,6);
triangle t=new triangle(p,p1,p2);
point p=new point(-1,3);
point p1=new point(4,2);
point p2=new point(3,3);
rectangle r=new rectangle(p,2,6);
triangle t=new triangle(p,p1,p2);
}
}
class point {
public int x,y;
public point() {}
public point(int x,int y)throws IllegalArgumentException
{
this.x=x;
this.y=y;
class point {
public int x,y;
public point() {}
public point(int x,int y)throws IllegalArgumentException
{
this.x=x;
this.y=y;
if(x<0||y<0)
throw new IllegalArgumentException(x+y+"x或y是无效参数!");
}
}
class rectangle extends point{
public int width,length;
//public point point1(3,6);
public rectangle(point point1,int length,int width)throws IllegalArgumentException
{
throw new IllegalArgumentException(x+y+"x或y是无效参数!");
}
}
class rectangle extends point{
public int width,length;
//public point point1(3,6);
public rectangle(point point1,int length,int width)throws IllegalArgumentException
{
this.length=length;
this.width=width;
if(length<0||width<0)
throw new IllegalArgumentException(length+width+"长或宽为无效参数!");
}
}
class triangle extends point{
public triangle(point point1,point point2,point point3)throws IllegalArgumentException
{
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)
throw new IllegalArgumentException("不能构成三角形,此为无效的参数!");
}
}
this.width=width;
if(length<0||width<0)
throw new IllegalArgumentException(length+width+"长或宽为无效参数!");
}
}
class triangle extends point{
public triangle(point point1,point point2,point point3)throws IllegalArgumentException
{
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)
throw new IllegalArgumentException("不能构成三角形,此为无效的参数!");
}
}
运行结果:
Exception in thread "main" java.lang.IllegalArgumentException: 2x或y是无效参数!
at point.<init>(dong.java:23)
at dong.main(dong.java:5)
at point.<init>(dong.java:23)
at dong.main(dong.java:5)
实验心得:实验中共处理三个异常,如果给的条件不符合其取值范围,就会出现抛出异常,之后就会进行异常捕捉和处理。
异常处理方法为IllegalArgumentException();
以上是关于异常的抛出,捕获并处理的主要内容,如果未能解决你的问题,请参考以下文章