zoukankan      html  css  js  c++  java
  • java:异常处理

    异常:编译正常,但运行出错,会中断正常指令流

    RuntimeException:运行时异常

    分为:uncheck exception、和check exception(除了RuntimeException以及子类以外的)

    uncheck exception

    class Test
    {
        public static void main(String args[]){
            System.out.println("1");
            int i = 1/0;
            System.out.println("2");
        }
    }

    异常处理:uncheck exception,try里面出异常,就跳到catch里面执行

    try{..}

    catch(){..}

    finally{..}

    class Test
    {
        public static void main(String args[]){
            try{
                int i = 1/0;
            }catch(Exception e){
                //出异常执行这里
                e.printStackTrace();
                System.out.println("2");
            }finally{
                //不管出不出异常都执行这里
                System.out.println("3");
            }
        }
    }

    throw抛出异常对象:

    class User
    {
        void setage(int age){
            if(age<0){
                RuntimeException r = new RuntimeException("年龄不为负");
                throw r;
            }
            System.out.println("函数末");
        }
    }
    class Test
    {
        public static void main(String args[]){
            User u = new User();
            u.setage(-3);
        }
    }

    throws声明一个函数有可能产生异常,调用的时候再处理异常

    class User
    {
        void setage(int age) throws Exception{
            if(age<0){
            Exception e = new Exception("年龄不为负");
            throw e;
            }
        }
    }
    class Test
    {
        public static void main(String args[]){
            User u = new User();
            try{
            u.setage(-3);
            }catch(Exception e){
                System.out.println(e);
            }
        }
    }
  • 相关阅读:
    【做题记录】区间排序—线段树
    【做题记录】CF1428E Carrots for Rabbits—堆的妙用
    线段树合并、分裂
    一、drf入门规范
    七、Django实战--图书管理系统搭建
    六、ORM模型层补充
    五、Django之模型层
    四、Django之模板层
    三、Django之视图层
    二、Django之路由层
  • 原文地址:https://www.cnblogs.com/tinyphp/p/3740820.html
Copyright © 2011-2022 走看看