首页 > 其他 > 详细

异常的简单概括

时间:2020-12-16 15:19:59      阅读:27      评论:0      收藏:0      [点我收藏+]

异常(Exception)

抛出异常

  • try监控区域,catch捕获异常,finally最终处理善后工作

  • ctrl alt T 自动生成

  • throw主动抛出异常,一般在方法中使用

  • throws定义方法时使用

        try {
                student.test(name);
            }catch (Exception e){
                
            }finally {
                
            }
    
    //主动抛出异常
    public void test (){
        if(){
            throw new Exception();
        }
    }
    
    public class Application {
        public static void main(String[] args) {
        //try catch进行捕获
        try {
                test2(3);
            } catch (Exception e) {
                e.printStackTrace();  
        } 
        }
        //方法主动抛出无法处理的异常
        public static void test2(int a) throws Exception{
            System.out.println(a);
        }
    }
    

自定义异常

  • 必须继承Exception类

    //异常类
    public class MyEx extends Exception{
        //传递数字>10 异常
        private int detail;
        public MyEx(int a){
            this.detail=a;
        }
    
        @Override
        public String toString() {
            return "MyEx{" +
                    "detail=" + detail +
                    ‘}‘;
        }
    }
    
    //异常方法
    static  void test3(int a) throws MyEx{
            if (a>10){
                throw new MyEx(a);
            }
        }
    
    //捕获异常
    public static void main(String[] args) {
            try {
                test3(12);
            } catch (MyEx e) {
                System.out.println(e);
            }
        }
    

异常的简单概括

原文:https://www.cnblogs.com/mr0fly/p/14143355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!