Get to know the java-10.5 stack track from scratch and throw an exception again
In this section, we will discuss stack tracing and re-throwing exceptions when exceptions occur.
1. Stack Tracing
Stack tracing can be printed in two ways:
(1) do not change the original code
package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new Exception(cause);} catch (Exception e) {e.printStackTrace();}}}
Output:
Java. lang. Exception: cause
At com. ray. ch10.Test. main (Test. java: 6)
(2) custom printing method stack Tracing
package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new Exception(cause);} catch (Exception e) {for (StackTraceElement element : e.getStackTrace()) {System.out.println(element.getMethodName());System.out.println(element.getFileName());System.out.println(element.getClassName());System.out.println(element.getLineNumber());}}}}
Output:
Main
Test. java
Com. ray. ch10.Test
6
Let's compare the output of the two code blocks. In fact, the output below is the component element of the above output.
2. Throw an exception again.
Sometimes we do not need to handle exceptions at a certain level, especially the mainstream mvc structure of web applications. Different layers manage different things, but sometimes I do not want to handle exceptions at a certain layer, then I need to throw an exception again.
Package com. ray. ch10; public class Test {private void test () throws Exception {try {throw new Exception (cause);} catch (Exception e) {throw e ;}} public static void main (String [] args) {try {new Test (). test ();} catch (Exception e) {e. printStackTrace (); System. out. println (Processing code );}}}
Output:
Java. lang. Exception: cause
At com. ray. ch10.Test. test (Test. java: 7)
At com. ray. ch10.Test. main (Test. java: 15)
Process Code
From the code and output, we can see that although I throw an exception in the test method, I don't care about it here, and then throw it out to the last time, which is handled in the main method.
Summary: This chapter mainly discusses stack tracing and rethrowing exceptions.