Exception処理のテクニック

1856 ワード

package test2;

public class Test {
    Log log = new Log();

    public void a1() {
        log.enter();
        a2();
        log.exit();
    }

    public void a2() {
        log.enter();
        a3("a");
        log.exit();
    }

    public void a3(String s) {
        log.enter();
        a4();
        log.exit();
    }

    public void a4() {
        log.enter();
        log.exit();
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Test t = new Test();
        t.a1();
    }
}

class Log {
    public void enter() {
        //System.out.println("enter");
        printTrace("enter");
    }

    public void exit() {
        //System.out.println("exit");
        printTrace("exit");
    }

    private void printTrace(String s) {
        try {
            throw new Exception("xxxx");
        } catch (Exception ex) {
            StackTraceElement[] stackTraces = ex.getStackTrace();
            if (stackTraces.length > 2) {
                System.out.println( s + " " +getMessage(stackTraces[2]));
            }
        }
    }

    private String getMessage(StackTraceElement st) {
        return st.getClassName() + "." + st.getMethodName();
        //return st.toString();
    }
}

 
実行後の出力は次のとおりです.
enter test2.Test.a1enter test2.Test.a2enter test2.Test.a3enter test2.Test.a4exit test2.Test.a4exit test2.Test.a3exit test2.Test.a2exit test2.Test.a1