Java oop创建自定义异常

package com.test;
/**
 *不管是在方法定义时就使用try catch,还是在定义方法时将异常抛出在调用方法时使用try catch都能达到效果 
 *
 */public class MyException02 extends Exception {
    //创建一个有参的构造方法
    public MyException02(String msg) {
        
    }
    
    //在创建方法时就使用try catch将异常捕获,在main方法中就只需要直接调用方法,而不需要对方法进行其他处理
    public static void f(String msg) {
        System.out.println("msg:" + msg);
        try {
            throw new MyException();
        } catch (MyException e) {
            //将错误信息发送到标准错误流,比直接将错误信息输出到System.out要好,因为后者有可能会被重定向
            e.printStackTrace(System.err);
        }finally {
            System.out.println("f()中finally输出的语句");
        }
    }
    
    //声明一个异常,在方法中将异常抛出,在main方法中再进行处理
    public static void g(String msg) throws MyException {
        System.out.println("msg:" + msg);
        throw new MyException();
    }
    
    public static void main(String[] args) {
        //直接调用方法,因为异常已经在方法中进行处理了
        f("传一个String给f");
        
        System.out.println();
        
        //在调用方法时再对方法中的异常使用try catch进行处理
        try {
            g("传一个String给G");
        } catch (Exception e) {
            e.printStackTrace(System.out);
        } finally {
            System.out.println("g()中finally输出的语句");
        }
        
    }
}
原文地址:https://www.cnblogs.com/zhangzimuzjq/p/11718265.html