Are you sure you want to read the exception information of Java ?, Read Java Information

Source: Internet
Author: User
Tags print format

Are you sure you want to read the exception information of Java ?, Read Java Information

The following error message is displayed:

java.lang.RuntimeException: level 2 exceptionat com.msh.demo.exceptionStack.Test.fun2(Test.java:17)at com.msh.demo.exceptionStack.Test.main(Test.java:24)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)Caused by: java.io.IOException: level 1 exceptionat com.msh.demo.exceptionStack.Test.fun1(Test.java:10)at com.msh.demo.exceptionStack.Test.fun2(Test.java:15)... 6 more

After studying Java for so many years, will you really read the exception information of Java? Can you tell the sequence of events during the exception throw process?

Write a demo test for the content to be internalized

The above exception information is generated in a demo:

package com.msh.demo.exceptionStack;import java.io.IOException;/** * Created by monkeysayhi on 2017/10/1. */public class Test {  private void fun1() throws IOException {    throw new IOException("level 1 exception");  }  private void fun2() {    try {      fun1();    } catch (IOException e) {        throw new RuntimeException("level 2 exception", e);    }  }  public static void main(String[] args) {    try {      new Test().fun2();    } catch (Exception e) {      e.printStackTrace();    }  }}

This time, I copied the complete file content so that the code line numbers in the article correspond to the actual line numbers one by one.

Based on the preceding exception information, the event sequence during the exception throw process is as follows:

How to read exception information

So, how to read the exception information? You need to understand the following points:

  • The exception stack is printed in the order of FILO. Exceptions located at the bottom of the printed content are first thrown, leading to exceptions being thrown at the top. The exception located at the top of the printed content is thrown at the latest and is not captured. Number from top to bottom, numberi+1The exception isiCauses of exceptions throwncause, Starting with "Caused.
  • Each exception in the exception stack is composed of the Exception name, detailed information, and path. The Exception name starts from the beginning of the line (or immediately following "Caused by"), followed by the details (to enhance readability, you need to provide appropriate details), starting from the next line, skip a tab, that is, a position in the path and a position in a row.
  • The path is printed in FIFO order. The path at the top of the printed content is first thrown out layer by this exception. The earliest position that passes through is the location where the exception is thrown, and the reverse debug can start from this place. The subsequent position is generally the entrance to the method call, which can be obtained from the method stack when JVM detects the exception. For cause, the printable path ends before being packaged into the next exception, and then prints "… 6 more ", indicating that cause is packaged abnormally. After that, it passes through six positions layer by layer, but these locations are the same as the paths of packaging exceptions, so this is omitted, and print it in the path of the packaging exception. "... 6 more "information is not important, can be ignored.

Now, let's go back and read the exception information in the example. Is it quite simple?

For better understanding, I have described the structure and composition elements of exception information as easily as possible, and may introduce some flaws. Reading exception information is a basic skill of Java Programmers. I hope you can internalize it and forget these lengthy descriptions.

If you do not understand it yet, we recommend that you track the creation and printing of an exception in person and use the sample code, which is simple but sufficient. The difficulty is that exceptions are the mechanism provided by JVM. You need to understand the implementation of JVM. At the underlying layer, many native methods are called, but tracing native code is not that convenient.

Why does the extension sometimes show only the Exception name "java. lang. NullPointerException" in the log, but there is no exception stack?

The exception information in the example contains three elements: Exception name, details, and path. However, due to JVM optimization, details and paths may be omitted.

This often occurs in the log of the server application. The same exception has been printed multiple times. If the same exception is printed, the JVM will omit the details and path queue, you can view the exception information.

This problem was encountered before monkey brother used the Yarn Timeline Server. Can you feel that way? Why is there no exception stack for the Exception name? No exception stack. How can I know where to throw an exception? I can't stop online services, but it depends on logs. Hello!

There are many identical cases on the Internet, such as NullPointerException loss of exception stack information. You can refer to this link for an experiment.

How to add member variables to an exception class

To properly express an exception, we sometimes need to customize the exception and add some member variables. When printing the exception stack, the necessary information is automatically added.

Trace and print the exception stack code:

...    public void printStackTrace() {        printStackTrace(System.err);    }...    public void printStackTrace(PrintStream s) {        printStackTrace(new WrappedPrintStream(s));    }...    private void printStackTrace(PrintStreamOrWriter s) {        // Guard against malicious overrides of Throwable.equals by        // using a Set with identity equality semantics.        Set<Throwable> dejaVu =            Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());        dejaVu.add(this);        synchronized (s.lock()) {            // Print our stack trace            s.println(this);            StackTraceElement[] trace = getOurStackTrace();            for (StackTraceElement traceElement : trace)                s.println("\tat " + traceElement);            // Print suppressed exceptions, if any            for (Throwable se : getSuppressed())                se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);            // Print cause, if any            Throwable ourCause = getCause();            if (ourCause != null)                ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);        }    }...

If you do not care about synchronization, you can see that the code for printing the Exception name and details is:

s.println(this);

During runtime, the JVM dynamically binds it to implement the multi-state call on this reference. If you continue tracing, the toString () method of this instance will be called. The lowest common ancestor class for all exceptions is the Throwable class, which provides the default toString () implementation. Most common exception classes do not overwrite this implementation, the custom exceptions can also directly inherit this implementation:

...    public String toString() {        String s = getClass().getName();        String message = getLocalizedMessage();        return (message != null) ? (s + ": " + message) : s;    }...    public String getLocalizedMessage() {        return getMessage();    }...    public String getMessage() {        return detailMessage;    }...

Obviously, the default print format is the exception information format of the example: Exception name (full qualified name) + detail information. DetailMessage is set when an exception is created. Therefore, if a custom member variable exists, we usually insert this variable in the toString () method. Referencecom.sun.javaws.exceptionsPackageBadFieldExceptionTo see how it Inserts custom member variables field and value:

public String toString() {  return this.getValue().equals("https")?"BadFieldException[ " + this.getRealMessage() + "]":"BadFieldException[ " + this.getField() + "," + this.getValue() + "]";}

Strictly speaking,BadFieldExceptionThe field member variable is not directly inserted into toString. However, this does not affect our understanding. Interested readers can read the source code on their own.

Summary

According to the exception information, debug is the basic skill of programmers. Here we have made a preliminary exploration on the reading and printing process of exception information, and will sort out common exception classes in the future, A better understanding of how to use exceptions to help us write clean code.

Java's fairly complete Exception Handling Mechanism is a double-edged sword. Using it can enhance the readability and robustness of the Code, and making the code more uncontrollable if it is not used well. For example, if you call the member method on a null pointer, an exception is thrown during runtime. This is natural-however, it is uncontrollable to wait for it to throw an exception at a certain time point (in fact, it is still "OK", but it is "uncertain" for debug ), or is it controllable to check and actively throw an exception at the beginning of the method? Further, what exceptions should be handled immediately and what should be thrown to the outer layer? When does an exception need to be encapsulated when it is thrown to the outer layer? Let's take a look at String # toLowerCase () and ProcessBuilder # start.

Java study and exchange QQ group: 589809992 chat prohibited, do not enter!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.