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