JavaでのカスタムException例外


Javaでカスタマイズされた例外は一般にExceptionから継承されているが,ここでは簡単に述べる.まず、カスタム例外クラスを継承します.
package cn.defineException;

//     :SeeWorld
public class SeeWorldException   extends Exception{
    public SeeWorldException(){

    }
    public SeeWorldException(String message){
        super(message);
    }
}

次にいくつかのテストクラスを作ってmainメソッドで観察します
package cn.defineException;

public class TestWorld {

    public void TestWorld1() throws SeeWorldException {
        throw new SeeWorldException("     ,     。");

    }

    public void TestWorld2() {
        try {
            TestWorld1();
        } catch (SeeWorldException e) {
            RuntimeException re = new RuntimeException("    ,    。");
            re.initCause(e);
            throw re;
        }
    }

    /**
     * TestWorld1()     TestWorld2()  TestWorld1(),    ,         。
     * main     TestWorld1(),    TestWorld2       
     * 
     * @param args
     */
    public static void main(String[] args) {

        TestWorld t = new TestWorld();
        try {
            t.TestWorld2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

これでいい:結果を見る
java.lang.RuntimeException:     ,    。
    at cn.defineException.TestWorld.TestWorld2(TestWorld.java:14)
    at cn.defineException.TestWorld.main(TestWorld.java:30)
Caused by: cn.defineException.SeeWorldException:      ,     。
    at cn.defineException.TestWorld.TestWorld1(TestWorld.java:6)
    at cn.defineException.TestWorld.TestWorld2(TestWorld.java:12)
    ... 1 more