//自定义异常TestException
@SuppressWarnings("serial")
class TestException extends Exception{
public TestException(String msg){
super(msg);
}
}
public class ExceptionOne{
public void test1(String msg)throws TestException{
throw new TestException(msg);
}
public void test2()throws Throwable{
try{
test1("test1出现异常!");
}catch(TestException e){
RuntimeException oneExe=new RuntimeException("test2出现异常");
throw oneExe.initCause(e);
}
}
public static void main(String[] args)throws Throwable{
ExceptionOne newExe=new ExceptionOne();
newExe.test2();
}
}
结果:
本文介绍了一个简单的自定义异常处理示例,通过创建一个名为 TestException 的自定义异常类,并在一个名为 ExceptionOne 的类中使用它来演示如何抛出和捕获自定义异常。此外,还展示了如何使用 initCause 方法将原始异常作为新异常的原因。
278

被折叠的 条评论
为什么被折叠?



