In the java language, the base class of the error class is java.lang.Error, and the base class of the exception class is java.lang.Exception.
1) Similarities: java.lang.Error and java.lang.Exception are both subclasses of java.lang.Throwable, so java.lang.Error and java.lang.Exception themselves and their subclasses can be used as objects of throw, such as: throw new MyError(); and throw new MyException(); where, the MyError class is a subclass of java.lang.Error, and the MyException class is a subclass of java.lang.Exception.
2) Differences: java.lang.Error itself and its subclasses do not require the support of the try-catch statement. The method can be returned at any time, as defined by the following method:
public String myMethod() { throw new MyError(); } Where MyError class is a subclass of java.lang.Error class.
java.lang.Exception itself and its subclasses need the support of try-catch statements, and the following method definition is wrong:
public String myMethod() { throw new MyException(); }The correct method is defined as follows:
public String myMethod() throws MyException { throw new MyException(); }Where the MyException class is a subclass of java.lang.Exception.
JAVA exception is an object created when an abnormal situation is encountered when a java program is running. It encapsulates exception information. The root class of the java exception is java.lang.Throwable. The entire class has two direct subclasses java.lang.Error and java.lang.Exception.Error is a serious error that cannot be recovered by the program itself. Exception indicates an exception error that can be caught and processed by the program. The JVM uses the method call stack to track a series of method calling processes in each thread, which saves the local information of each calling method. For independent JAVA programs, it can all the way to the main method of the program. When a new method is called, the JVM places the stack structure describing the method on the top of the stack, and the method at the top of the stack is the correct execution method. When a J After the AVA method is executed normally, the JVM returns to the stack structure of the method from the call stack, and then continues to process the previous method. If the java method throws an exception during the execution of the code, the JVM must find the catch block code that can catch the exception. It first checks whether the current method has such a catch code block, and if it exists, execute the catch code block. Otherwise, the JVM returns to the stack structure of the method at the call stack, and continues to find the appropriate catch code block in the previous method. Finally, if the JVM chases up to the main() method, that is, it keeps throwing the exception to the main() method, and still has not found the code block for the exception handler, the thread will terminate abnormally. If the thread is the main thread, the application will also terminate accordingly. At this time, the JVM will throw the exception directly to the user, and the original exception information will be seen on the user terminal.
Java.lang.throwable source code analysis
package java.lang; import java.io.*; /** * * Throwable is the parent class of all Error and Exceptiong* Note that it has four constructors: * Throwable() * Throwable(String message) * Throwable(Throwable cause) * Throwable(String message, Throwable cause) * */ public class Throwable implements Serializable { private static final long serialVersionUID = -3042686055658047285L; /** * Native code saves some indication of the stack backtrace in this slot. */ private transient Object backtrace; /** * Information describing this exception*/ private String detailMessage; /** * Indicates that the current exception is caused by the Throwable* If null means that the exception is not caused by other Throwable* If this object is the same as itself, it indicates that the object causing the exception has not been initialized*/ private Throwable cause = this; /** * Array describing the exception track*/ private StackTraceElement[] stackTrace; /** * Constructor, the cause object is not initialized can be initialized in the future using initCause* fillInStackTrace can be used to initialize an array of its exception tracks*/ public Throwable() { fillInStackTrace(); } /** * Constructor*/ public Throwable(String message) { //Fill the exception track array fillInStackTrace(); //Initialize exception description information detailsMessage = message; } /** * Constructor, cause represents the cause object*/ public Throwable(String message, Throwable cause) { fillInStackTrace(); detailMessage = message; this.cause = cause; } /** * Constructor*/ public Throwable(Throwable cause) { fillInStackTrace(); detailMessage = (cause==null ? null : cause.toString()); this.cause = cause; } /** * Get detailed information*/ public String getMessage() { return detailedMessage; } /** * Get detailed information*/ public String getLocalizedMessage() { return getMessage(); } /** * Get the cause object*/ public Throwable getCause() { return (cause==this ? null : cause); } /** * Initialize the cause object. This method can only be called once without initialization*/ public synchronized Throwable initCause(Throwable cause) { // If it is not an uninitialized state, throw an exception if (this.cause != this) throw new IllegalStateException("Can't overwrite cause"); //The cause object to be set is equal to itself and throw an exception if (cause == this) throw new IllegalArgumentException("Self-causation not allowed"); //Set the cause object this.cause = cause; //Return the set cause object return this; } /** * String representation*/ public String toString() { String s = getClass().getName(); String message = getLocalizedMessage(); return (message != null) ? (s + ": " + message) : s; } /** * Print out the error track*/ public void printStackTrace() { printStackTrace(System.err); } /** * Print out the error track*/ public void printStackTrace(PrintStream s) { synchronized (s) { //Calling the toString method of the current object s.println(this); //Get the exception track array StackTraceElement[] trace = getOurStackTrace(); //Print out the string representation of each element for (int i=0; i < trace.length; i++) s.println("/tat " + trace[i]); //Get the cause object Throwable ourCause = getCause(); //Recursively print out the information of the cause object if (ourCause != null) ourCause.printStackTraceAsCause(s, trace); } } /** * Print the cause object information* @param s Printed stream* @param causedTrace Exception track with exception caused by this object*/ private void printStackTraceAsCause(PrintStream s, StackTraceElement[] causedTrace) { //Get the current exception track StackTraceElement[] trace = getOurStackTrace(); //m is the last element of the current exception track array, //n is the last element of the exception track array of the exception caused by the current object int m = trace.length-1, n = causedTrace.length-1; //Loop from behind the two arrays respectively. If it is equal, loop until inequality or the array reaches the beginning while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) { m--; n--; } //The same number int framesInCommon = trace.length - 1 - m; //Print out different error traces s.println("Caused by: " + this); for (int i=0; i <= m; i++) s.println("/tat " + trace[i]); //If there is the same number, print out the same number if (framesInCommon != 0) s.println("/t... " + framesInCommon + " more"); //Get the cause of this object and print out the information recursively Throwable ourCause = getCause(); if (ourCause != null) ourCause.printStackTraceAsCause(s, trace); } /** * Print out the error track*/ public void printStackTrace(PrintWriter s) { synchronized (s) { s.println(this); StackTraceElement[] trace = getOurStackTrace(); for (int i=0; i < trace.length; i++) s.println("/tat " + trace[i]); Throwable ourCause = getCause(); if (ourCause != null) ourCause.printStackTraceAsCause(s, trace); } } /** * Print the information about the cause object*/ private void printStackTraceAsCause(PrintWriter s, StackTraceElement[] causedTrace) { // assert Thread.holdsLock(s); // Compute number of frames in common between this and caused StackTraceElement[] trace = getOurStackTrace(); int m = trace.length-1, n = causedTrace.length-1; while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) { m--; n--; } int framesInCommon = trace.length - 1 - m; s.println("Caused by: " + this); for (int i=0; i <= m; i++) s.println("/tat " + trace[i]); if (framesInCommon != 0) s.println("/t... " + framesInCommon + " more"); // Recurse if we have a cause Throwable ourCauses = getCause(); if (ourCause != null) ourCause.printStackTraceAsCause(s, trace); } /** * Fill out the exception track*/ public synchronized native Throwable fillInStackTrace(); /** * Return a copy of the current exception track*/ public StackTraceElement[] getStackTrace() { return (StackTraceElement[]) getOurStackTrace().clone(); } /** * Get the current exception track */ private synchronized StackTraceElement[] getOurStackTrace() { //If this method is called for the first time, the exception track array is initialized if (stackTrace == null) { //Get the exception track depth int depth = getStackTraceDepth(); //Create a new array of exception tracks and fill it stackTrace = new StackTraceElement[depth]; for (int i=0; i < depth; i++) stackTrace[i] = getStackTraceElement(i);//Get the exception track of the specified bit point} return stackTrace; } /** * Set exception track*/ public void setStackTrace(StackTraceElement[] stackTrace) { //Copy the setting parameter StackTraceElement[] defendensiveCopy = (StackTraceElement[]) stackTrace.clone(); //If the setting parameter has empty elements, an exception will be thrown for (int i = 0; i < defensiveCopy.length; i++) if (defensiveCopy[i] == null) throw new NullPointerException("stackTrace[" + i + "]"); //Set the exception track of the current object this.stackTrace = defensiveCopy; } /** * The depth of the exception track, 0 means that it is not possible to obtain */ private native int getStackTraceDepth(); /** * Get the exception track of the specified bit point*/ private native StackTraceElement getStackTraceElement(int index); private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { getOurStackTrace(); s.defaultWriteObject(); } }