exception

 

 

 

 

 

 try,catch方式:

package com.zrm.arrays;

public class Exception01 {
    public static void main(String[] args) {
        //处理的代码块(try中的代码块可能出现异常)
        try {
            System.out.println(1 / 0);
        }
        //catch,捕获产生的异常
        catch (Exception e) {
            e.printStackTrace();
        }
        //finally,不管这段代码中是否出现异常,最终都会执行finally中的代码
        finally {
            System.out.println("welcome to use");
        }
    }
}

申明异常

package com.zrm.arrays;

public class Exception02 {
    static void method(String gender) throws Exception {
        if (gender == "man") {
            System.out.println("man");
        } else if (gender == "woman") {
            System.out.println("woman");
        } else {
            throw new Exception("gender is error");//申明异常
        }
    }

    public static void main(String[] args) throws Exception {//申明异常
        Exception02.method("女");
    }
}

自定义异常:

package com.zrm.arrays;

//自定义异常,继承Exception类
public class Exception03 extends Exception {
    public Exception03() {
        System.out.println("gender is error");
    }

    public Exception03(String msg) throws Exception {
        System.out.println(msg);
    }
}

 

posted @ 2019-09-02 21:40  26417  阅读(158)  评论(0编辑  收藏  举报