异常机制

异常

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nodp9xok-1606719385330)(C:\Users\11096\Desktop\acadc9cad734329e60e788a06fd7420.png)]

try catch finally throw throws

package com.breet.exception;

public class Test {

    public static void main(String[] args) {
        int a=1;
        int b=0;
        //假设要捕获多个异常:从小到大!
        try {//try是监控区域
            System.out.println(a/b);
        }catch (Error e){
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        } catch (Throwable e){//catch捕获异常  catch(想要捕获的异常类型)Throwable是最大的异常
            System.out.println("Throwable");
        }finally {//处理善后工作
            System.out.println("finally");
        }

        //finally可以不要,假设IO,资源,关闭!

    }
}
package com.breet.exception;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.w3c.dom.ls.LSOutput;

public class Test2 {
    public static void main(String[] args) {

        Test2 test2=new Test2();
        //ctrl+alt+t
        try {
            test2.test(2,0);
        } catch (ArithmeticException e) {
            System.out.println("程序发生异常,除数b不能为0");//打印错误的栈信息
        } finally {
            System.out.println("finally");
        }
    }
    //假设方法中处理不了这个异常,则主动向上抛出这个异常
public void test(int a,int b)throws ArithmeticException {
        if(b==0){
            throw new ArithmeticException();
        }
        else {
            System.out.println(a/b);
        }
}


}
package com.breet.exception.demo02;
//自定义的异常类
public class MyException extends Exception {

    //传递数字>10
    private int detail;

    public MyException(int a) {
        this.detail=a;

    }

    //toString:异常的打印信息

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
package com.breet.exception.demo02;

public class Test3 {
    public static void main(String[] args) {
        try{
            test(11);

        }catch (MyException e){
            System.out.println("Myexception="+e);
        }
        finally {
            System.out.println("finally");
        }
    }

    //可能会存在异常的方法
    static void test(int a) throws MyException{
        if(a>10){
            throw new MyException(a);
        }
        else{
            System.out.println(a);
        }
    }
}
           throw new MyException(a);
        }
        else{
            System.out.println(a);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值