异常

异常

ERROR 通常是灾难性的致命的错误,是程序无法控制和处理的

Exception 通常情况下是可以被程序处理的

抛出异常 - 捕获异常

五个关键字 :try catch finally throw throws

public class Test {

    public static void main(String[] args) {

        int a = 1;
        int b = 0;

        //快捷键:选择代码段 Ctrl+Alt+T 对代码块进行包装(if-else do-while try-catch等)
        //try监控区域
        try {
            //主动抛出异常,throw一般在方法中使用 -- throws在方法体之前定义,监控整个方法
            // -- throw throws 不一样!
            if (b==0){
                throw new ArithmeticException();// throw的异常也通过catch捕获
            }

            new Test().a();
            System.out.println(a/b);
            //try中出现第一个异常后的代码不被执行,而是直接跳转到catch进行捕获
        }
        //异常捕获 catch(可捕获异常类型)
        catch (StackOverflowError e){
            System.out.println("出错了,死循环导致栈溢出");
        }
        catch (ArithmeticException e){
            System.out.println("出错了,被除数不能为零");
        }
        catch (Exception e){
            System.out.println("捕获到Exception");
        }
        //范围大的异常最后捕获 -- Throwable范围最大
        catch (Throwable e){
            System.out.println("捕获到Throwable");
        }
        finally {
            System.out.println("finally");
        }
        //处理善后工作,可以不写,如果有finally则无论是否出现异常finally都会被执行
    }

    public void a() throws Exception{
        b();
    }
    public void b(){
        a();
    }
}

异常类型

自定义异常

自定义异常类必须继承(extends)父类Exception类

//自定义异常
public class MyException extends Exception{

    //传递数字 >10 判定异常
    private int detail;

    //alt+insert 创建构造器
    public MyException(String message, int detail) {
        super(message);
        this.detail = detail;
    }

    //alt+insert 重写toString -- 异常的打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

public class Test {
    static void test(int a) throws MyException{

        System.out.println("传递的参数为"+a);

        if(a>10){
            throw new MyException("异常抛出",a);
        }

        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            System.out.println("异常信息:"+e); //MyException{detail=11}
        }
    }
}
posted @   LaViez  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示