异常的抛出,捕获并处理

异常的抛出,捕获并处理

 

 

源程序

 

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);

 }

}
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+"xy是无效参数!"); 
}
}
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("不能构成三角形,此为无效的参数!");
}
}

 

运行结果:

Exception in thread "main" java.lang.IllegalArgumentException: 2xy是无效参数!
 at point.<init>(dong.java:23)
 at dong.main(dong.java:5)

 

心得:

    1. 程序通过try{}捕捉异常,try如果有异常发生,程序的运行便会中断,抛出异常类所产生的对象
    2. 在检测异常时,要注意将之前的异常注释掉,因为当程序出现异常时,就直接中断程序,就无法测试后面的异常现象

转载于:https://www.cnblogs.com/MWH0979/p/10927578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值