throws和throw的使用及其区别

throws和throw的使用及其区别

throws关键字用于修饰方法体中可能产生的若干个异常,修饰位置置于方法名字的后面,如public void f() throws Exception1,Exception2{},而且要在该方法中给出具体的异常操作,throw关键字正用于抛出具体异常对象,它通常要和throws或try{}catch{}配套使用。

示例代码 ##

定义一个我们生活中收入和支出的例子,收入的钱是正数,而支出的钱是负数,若违反此规则,则抛
出一个异常。

/**
 * 
 * 定义一个处理异常的异常类
 *
 */
public class AriException extends Exception{

    private String meassage;

    public AriException(double in,double out) {
        meassage = "收入"+in+"应为正数或"+"支出"+out+"应为负数。";
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return meassage;
    }
}

  

public class Test {

    private double sum;

    public static void main(String[] args) {

        Test test = new Test();
        try {
            test.calculate(5, -2);
            System.out.println(test.getSum());
            test.calculate(5, 6);
            System.out.println(test.getSum());
        } catch (AriException e) {
            // TODO Auto-generated catch block
            System.out.println(e.toString());
        }
    }

    public void calculate(double in,double out) throws AriException{//throws声明方法的可能产生的异常
        if(in<0 || out>0) {
            throw new AriException(in, out);//用throw抛出具体的异常
        }
        sum = in+out;
    }

    public double getSum() {
        return sum;
    }
}

输出结果:

当数据违反异常时,则会在AriException中进行相应的处理。

throw和throws的区别:
1.throw用于抛出具体异常对象,而throws修饰方法。 
2.throw不能单独使用,只能配合throws或try{}catch{}使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值