preface

Exceptions are some errors in a program, but not all errors are exceptions, and errors can sometimes be avoided.

Architecture of exceptions:

The Thorwable class is the superclass for all exceptions and errors, with two subclasses Error and Exception representing errors and exceptions, respectively. The Exception class is classified into RuntimeException and non-runtime Exception. These two types of exceptions are largely different, and are also called Unchecked Exception and Checked Exception.

Runtime and non-runtime exceptions:

Runtime exceptions are RuntimeException class and its subclasses abnormalities, such as NullPointerException, IndexOutOfBoundsException, these exceptions are not checked exception, in the program can choose to capture processing, also can not deal with. These exceptions are usually caused by program logic errors, and programs should logically avoid them as much as possible.

Non-runtime exceptions are exceptions other than RuntimeException and are of type to the Exception class and its subclasses. An exception that must be handled syntactically. If not handled, the program will fail to compile. Such as IOException, ClassNotFoundException, and user-defined exceptions.

Custom exceptions:

Sometimes there are special exceptions in the program, and these exceptions are not described by Java and encapsulate objects, for these special exceptions can be in accordance with the Idea of Java encapsulation. Encapsulate unique exceptions according to the Java exception mechanism.

Exception systems have a unique property: throwability: can be operated by the throw keyword. If a custom exception is thrown, the object must inherit Throwable or a subclass of Throwable before it can be thrown.

Custom exceptions generally inherit Exception or RuntimeException, depending on whether you need to catch the Exception.

In the exception often need to encapsulate the exception information, check the exception source code, find their parent class constructor about the exception information operation, then in their own definition of the exception need to pass these information to the parent class, let the parent class help us to encapsulate.

Class NoAgeException extends RuntimeException{/* The reason for defining a constructor is because you see an exception description class in Java that provides an initialization method for a problem object. */ NoAgeException(){ super(); } NoAgeException(String message) { super(message); // If a custom exception requires exception information, it can do so by calling the parent class's constructor with a string argument. }}Copy the code

Exception handling:

There are two main components of exception handling: throwing and catching exceptions. These two elements jointly realize the abnormal transfer of program control flow.

There are two types of exceptions thrown: explicit and implicit.

The subject of an explicit exception throw is an application, which refers to the use of the “throw” keyword in a program. Manually throw exception instances.

The topic of implicit exception throwing is the Java VIRTUAL machine. When the Java virtual machine encounters an exception that cannot be continued during execution, it automatically throws an exception. Java virtual machine, for example, when performing read array operations, found that the input index value is negative, it throws array index cross-border anomalies (ArrayIndexOutOfBoundsException).

Catching exceptions involves the following three code blocks:

1. Try code block: used to mark code for exception monitoring.

Catch block: Follows a try block to catch the type of exception that is raised within the try block. In addition to declaring the type of exception caught, the catch block defines an exception handler for that type of exception. In Java, a try block can be followed by multiple catch blocks to catch different exceptions. The Java virtual machine matches exception handlers from top to bottom. Therefore, the type of exception caught by the preceding catch block cannot override the following, or the compiler will report an error.

3. Finally block: Used after a try and catch block to declare a piece of code that must run. It is designed to avoid skipping some critical cleanup code. For example, close an open system resource.

In the case of normal program execution, this code is executed after the try block. Otherwise, in the case of a try block throwing an exception, if the exception is not caught, the finally block will run directly and re-throw the exception after running.

If the exception is caught by a catch block, the finally block runs after the catch block. In some unfortunate cases, if a catch block also raises an exception, the finally block will also execute and throw the exception that the catch block raises. In an extremely unfortunate case, the finally block also raises an exception, and you have to break the execution of the current finally block and throw an exception.

Non-runtime exception:

Capture format:

Try {// The statement to be tested. } catch(exception class variable)// parameter. {// Exception handling statement. } finally {// The statement that must be executed. }Copy the code
Class Demo{/* Report to the caller if a problem occurs while defining a function. You can declare it by using the throws keyword on functions. */ void show(int x)throws Exception { if(x>0){ throw new Exception(); }else{ System.out.println("show run"); Class ExceptionDemo{public static void main(String[] args)//throws Exception// Continue the declaration on the caller. { Demo d = new Demo(); try { d.show(1); // When a method that declares an exception is called, there must be a handler. Either capture or declare. } catch (Exception ex)// What do I need to define in parentheses? A reference to any question thrown by the other side is defined in parentheses. {system.out. println(" exception occurred "); } System.out.println("Hello World!" ); }}Copy the code

Runtime exception:

Describe a rectangle.

  • Attributes: length and width.
  • Behavior: Get area.

Consider robustness. In case the length and width values are illegal. Describe the problem, encapsulate the problem into objects, and represent it in the way of exceptions.

class NoValueException extends RuntimeException{ NoValueException() { super(); } NoValueException(String message) { super(message); } } class Rec{ private int length; private int width; Rec (int length, int width) {if (length < = 0 | | width < = 0) {/ / throw an exception, but without saying, don't need to deal with the caller. You need to stop the caller as soon as the problem occurs and let him change the code. Throw new NoValueException(" long or wide values are invalid "); } this.length = length; this.width = width; } /** defines the area function. */ public int getArea() { return length*width; }} class ExceptionTest{public static void main(String[] args) {Rec r = new Rec(-3,4); int area = r.getArea(); System.out.println("area="+area); }}Copy the code

The JVM’s catch exception mechanism

In the bytecode generated by compilation, each method comes with an exception table. In the exception table, each entry represents an exception handler and consists of Pointers to FROM, to, and target, as well as the type of exception caught. The values of these Pointers are the bytecode index (BCI) used to locate the bytecode. The FROM and to Pointers indicate the scope monitored by the exception handler, such as the scope covered by the try code block. The target pointer points to the starting position of the exception handler, such as the starting position of the catch block.

When the program raises an exception, the JVM iterates through all the entries in the exception table from top to bottom. When the index value of the bytecode that triggered the exception is within the monitored range of an exception table entry, the JVM determines whether the exception thrown matches the exception that the entry is trying to catch. If a match is found, the JVM shifts control flow to the bytecode pointed to by the entry target pointer. If the JVM still does not match the exception handler after iterating through all the entries, it will pop up the Java stack frame corresponding to the current method and repeat this in the caller. In the worst case, the JVM needs to traverse the exception table for all methods on the current thread’s Java stack.

Finally code blocks can be complicated to compile. The current version of the Java compiler copies the contents of the finally block and places them in the exit of all normal and exception execution paths of the try-catch block. For exception execution paths, the Java compiler generates one or more exception table entries, monitors the entire try-catch block, and catches all kinds of exceptions. The target pointer to these exception table entries will point to another copy of the finally code block. And, at the end of the finally block, the Java compiler rethrows the caught exception.

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!