java:异常处理

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

RuntimeException:运行时异常

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

uncheck exception

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

java:异常处理

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

try{..}

catch(){..}

finally{..}

java:异常处理
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");
        }
    }
}
java:异常处理

throw抛出异常对象:

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

java:异常处理

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

java:异常处理
class User
{
    void setage(int age) throws Exception{
        if(age<0){
        Exception e = new Exception("年龄不为负");
        throw e;
        }
    }
}
java:异常处理
java:异常处理
class Test
{
    public static void main(String args[]){
        User u = new User();
        try{
        u.setage(-3);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}
java:异常处理

java:异常处理,布布扣,bubuko.com

java:异常处理

上一篇:[leetcode]Copy List with Random Pointer @ Python


下一篇:[python] python单元测试经验总结