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)
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)
本文链接:http://task.lmcjl.com/news/10762.html