zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Java异常(2)- 捕获和抛出异常

2023-02-18 16:23:22 时间

异常处理五个关键字:try,catch,finally,throw,throws

 

捕获异常

try、catch、finally

package oop.demo10;

public class Outer {
    public static void main(String[] args) {
        int a = 1;
        int b =0;

        //捕获多个异常:范围从小到大
        try {//try监控区域
            System.out.println(a/b);
        } catch (Error e) {//catch(想要捕获的异常类型)捕获异常
            System.out.println("Error");
        } catch (Exception e) {
            System.out.println("Exception");
        }catch (Throwable e) {
            System.out.println("Throwable");
        }finally {//处理善后工作
            System.out.println("finally");
        }
    }
}

选中代码:Ctrl+Alt+T快捷键

抛出异常

throw:一般用于方法中抛出异常

throws:在方法上抛出异常

package oop.demo10;

public class Outer {
    public static void main(String[] args) {
        new Outer().test(1,0);
    }

    //假设方法中,处理不了这个异常。那就通过throws在方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException();//throw 主动抛出异常
        }else{
            System.out.println(a/b);
        }
    }
}