java异常处理之抛出异常

抛出处理

定义一个功能,进行除法运算例如(div(int x,int y))如果除数为0,进行处理。

功能内部不想处理,或者处理不了。就抛出使用throw new Exception(“除数不能为0”); 进行抛出。抛出后需要在函数上进行声明,告知调用函数者,我有异常,你需要处理如果函数上不进行throws 声明,编译会报错。例如:未报告的异常 java.lang.Exception;必须对其进行捕捉或声明以便抛出throw new Exception(“除数不能为0”);

public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。

        if (y == 0) {
    throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
        }
        System.out.println(x / y);
        System.out.println("除法运算");
    }

main方法中调用除法功能

调用到了一个可能会出现异常的函数,需要进行处理。
        1:如果调用者没有处理会编译失败。
如何处理声明了异常的函数。
        1:try{}catch(){}

    public static void main(String[] args) {

        try {
            div(2, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("over");

    }

    public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。

        if (y == 0) {
    throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
        }
        System.out.println(x / y);
        System.out.println("除法运算");
    }
}

2:继续抛出throws

class Demo9 {

    public static void main(String[] args) throws Exception {
        div(2, 0);
        System.out.println("over");
    }

    public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。
    if (y == 0) {
        throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
    }

        System.out.println(x / y);
        System.out.println("除法运算");
    }
}

throw和throws的区别
1. 相同:都是用于做异常的抛出处理的。
2. 不同点:
1. 使用的位置: throws 使用在函数上,throw使用在函数内
2. 后面接受的内容的个数不同:
1. throws 后跟的是异常类,可以跟多个,用逗号隔开。
2. throw 后跟异常对象。

//throws 处理
public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        obj.wait();

    }
public static void main(String[] args) {

        //try catch 处理
        Object obj = new Object();
        try {
            obj.wait();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }

总结

  1. try语句不能单独存在,可以和catch、finally组成 try…catch…finally、try…catch、try…finally三种结构。
  2. catch语句可以有一个或多个,finally语句最多一个,try、catch、finally这三个关键字均不能单独使用。
  3. try、catch、finally三个代码块中变量的作用域分别独立而不能相互访问。如果要在三个块中都可以访问,则需要将变量定义到这些块的外面。
  4. 多个catch块时候,Java虚拟机会匹配其中一个异常类或其子类,就执行这个catch块,而不会再执行别的catch块。(子类在上,父类在下)。
  5. throw语句后不允许有紧跟其他语句,因为这些没有机会执行。
  6. 如果一个方法调用了另外一个声明抛出异常的方法,那么这个方法要么处理异常,要么声明抛出。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值