class SelfException extends RuntimeException {
SelfException() {
}
SelfException(String msg) {
super(msg);
}
}
public class PrintStackTraceTest {
public static void main(String[] args) {
firstMethod();
}
public static void firstMethod() {
secondMethod();
}
public static void secondMethod() {
thirdMethod();
}
public static void thirdMethod() {
throw new SelfException("自定义异常信息");
}
}
上面程序中 main 方法调用 firstMethod,firstMethod 调用 secondMethod,secondMethod 调用 thirdMethod,thirdMethod 直接抛出一个 SelfException 异常。运行上面程序,会看到如下所示的结果。
Exception in thread "main" Test.SelfException: 自定义异常信息
at Test.PrintStackTraceTest.thirdMethod(PrintStackTraceTest.java:26)
at Test.PrintStackTraceTest.secondMethod(PrintStackTraceTest.java:22)
at Test.PrintStackTraceTest.firstMethod(PrintStackTraceTest.java:18)
at Test.PrintStackTraceTest.main(PrintStackTraceTest.java:14)
下面例子程序示范了多线程程序中发生异常的情形。关于多线程可以参考教程的《Java多线程编程》一章,也可忽略本节关于多线程的内容,学习完多线程在了解本节内容。
public class ThreadExceptionTest implements Runnable {
public void run() {
firstMethod();
}
public void firstMethod() {
secondMethod();
}
public void secondMethod() {
int a = 5;
int b = 0;
int c = a / b;
}
public static void main(String[] args) {
new Thread(new ThreadExceptionTest()).start();
}
}
运行上面程序,会看到如下运行结果。
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at Test.ThreadExceptionTest.secondMethod(ThreadExceptionTest.java:14)
at Test.ThreadExceptionTest.firstMethod(ThreadExceptionTest.java:8)
at Test.ThreadExceptionTest.run(ThreadExceptionTest.java:4)
at java.lang.Thread.run(Unknown Source)
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有