第十一话-Java异常

异常:Error和Exception

  1. 简单分类

  1. 异常体系结构

  1. Error

  1. Exception

捕获和抛出异常

package com.xie.exception;

public class Test {
    public static void main(String[] args) {
        try {//try监控区域
            new Test().test(1,0);
        } catch (ArithmeticException e) {//catch捕获异常
            e.printStackTrace();
            System.out.println("aaaaaaaaaa");
        } finally {//处理善后工作
            System.out.println("-------");
        }
    }

    public void test(int a,int b) throws ArithmeticException{
        if(b == 0){
            throw new ArithmeticException();
        }else {
            System.out.println(a/b);
        }
    }
}

注:异常可以捕获多个,但必须从小到大捕获,Throwable>Exception=Error

自定义异常

package com.xie.exception.demo01;

public class MyException extends Exception{

    private int detail;

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

    //异常信息打印
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
package com.xie.exception.demo01;

public class Test {
    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            e.printStackTrace();//finally执行之后再打印
            System.out.println("MyException-->"+e);
        } finally {
            System.out.println("finally");
        }
    }

    static void test(int a) throws MyException {
        System.out.println("参数:" + a);
        if(a > 10){
            throw new MyException(a);
        }else {
            System.out.println("OK");
        }
    }
}

posted @   少年阿川  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示