Deep understanding of Java exception handling mechanism and Application

1. Introduction

Try... Catch... Finally I'm afraid it's a familiar sentence, and it feels very simple to use, and it seems very easy to understand logically. However, the "lesson" I personally experienced tells me that this thing is not as simple and obedient as imagined. Don't believe it? Then look at the following code and "guess" what the result will be after it is executed? Don't look back at the answer or execute the code to see the real answer. If your answer is correct, you don't have to waste time reading this article.

What's your answer? Is that the answer below?

i=2 i=1 testEx2,catch exception testEx2,finally; return value=false testEx1,catch exception testEx1,finally; return value=false testEx,catch exception testEx,finally; return value=false

If your answer is really as mentioned above, you are wrong, I suggest you take a closer look at this article or take the above code to modify, execute and test according to different situations. You will find that many things are not as simple as originally thought. Now publish the correct answer:

i=2 i=1 testEx2,finally; return value=false testEx,finally; return value=false

Note:

Finally statement block should not have return. The above return is better to use other statements to handle related logic.

2. Java exception

Exceptions refer to unexpected conditions, such as file missing, network connection failure, illegal parameters, etc. An exception is an event that occurs during program operation and interferes with the normal instruction flow. Java describes various exceptions through many subclasses of the throwable class in the API. Therefore, Java exceptions are objects, instances of throwable subclasses, and describe the error conditions that appear in a piece of code. When the condition is generated, the error throws an exception.

Java exception class hierarchy diagram:

Figure 1 Java exception class hierarchy

In Java, all exceptions have a common ancestor, throwable. Throwable specifies the commonality of any problem that can be transmitted through the Java application through the exception propagation mechanism available in the code.

Throwable: there are two important subclasses: exception and error. Both are important subclasses of Java exception handling, and each contains a large number of subclasses.

Error: it is an error that cannot be handled by the program, indicating a more serious problem in running the application. Most errors have nothing to do with the operation performed by the coder, but indicate a problem with the JVM (Java virtual machine) when the code is running. For example, Java virtual machine running error (virtual machineerror). Outofmemoryerror will appear when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine (JVM) will generally choose thread termination.

These errors indicate that the failure occurred in the virtual machine itself or when the virtual machine tried to execute the application, Such as Java virtual machine running error and class definition error (NoClassDefFoundError), etc. these errors are not traceable because they are outside the control and processing capacity of the application, and most of them are conditions that are not allowed to occur when the program is running. For a reasonably designed application, even if an error does occur, it should not try to deal with the abnormal conditions caused by it. In Java, errors are common Subclass description of error.

Exception: an exception that can be handled by the program itself.

The exception class has an important subclass runtimeException. The runtimeException class and its subclasses represent errors caused by "JVM common operations". For example, if you try to use a null object reference, divide by zero, or array out of bounds, run-time exceptions (NullPointerException, arithmeticexception) and arrayindexoutofboundexception are thrown, respectively.

Note: the difference between exceptions and errors: exceptions can be handled by the program itself, while errors cannot be handled.

Generally, Java exceptions (including exceptions and errors) are divided into checked exceptions and unchecked exceptions.

Verifiable exception (the exception that the compiler requires to handle): a reasonable and tolerable exception that is easy to occur when the correct program is running. Although a verifiable exception is an exception, its occurrence can be predicted to a certain extent, and once this exception occurs, it must be handled in some way.

Except runtimeException and its subclasses, other exception classes and their subclasses belong to searchable exceptions. The characteristic of this exception is that the java compiler will check it, that is, when this kind of exception may occur in the program, either catch it with a try catch statement or throw it with a throw clause declaration, otherwise the compilation will not pass.

Non observable exceptions (exceptions that the compiler does not require forced handling): including runtime exceptions (runtimeException and its subclasses) and errors (errors).

Exceptions are divided into two categories: runtime exceptions and non runtime exceptions (compilation exceptions). The program should handle these exceptions as much as possible.

Runtime exceptions: they are all exceptions of runtimeException class and its subclasses, such as NullPointerException (null pointer exception), indexoutofboundsexception (subscript out of bounds exception), etc. these exceptions are not checked. The program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions as much as possible from a logical point of view.

The characteristic of runtime exception is that the java compiler will not check it, that is, when such an exception may occur in the program, it will be compiled even if it is not caught with the try catch statement or thrown with the throw clause declaration.

Non runtime exception (compilation exception): it is an exception other than runtimeException, which belongs to exception class and its subclasses. From the perspective of program syntax, it is an exception that must be handled. If it is not handled, the program cannot be compiled. For example, IOException, sqlexception and user-defined exception exceptions, exception checking is not customized in general.

3. Exception handling mechanism

In Java applications, the exception handling mechanism is to throw exceptions and catch exceptions.

Throw exception: when a method throws an exception due to an error, the method creates an exception object and delivers it to the runtime system. The exception object contains exception information such as exception type and program state when the exception occurs. The runtime system is responsible for finding and executing the code to handle exceptions.

Catch exception: after the method throws an exception, The runtime system will turn to finding the appropriate exception handler (exception handler). A potential exception handler is a collection of methods stored in the call stack in turn when an exception occurs. When the exception type that the exception handler can handle is consistent with the exception type thrown by the method, it is the appropriate exception handler. The runtime system starts with the method with the exception, and checks the methods in the call stack in turn until it finds the method with the appropriate exception The method of the constant processor is and executed. When the runtime system traverses the call stack without finding a suitable exception handler, the runtime system terminates. At the same time, it means the termination of Java programs.

For runtime exceptions, errors or verifiable exceptions, Java technology requires different exception handling methods.

Due to the non availability of runtime exceptions, in order to more reasonably and easily implement the application, Java stipulates that runtime exceptions will be automatically thrown by the Java runtime system, allowing the application to ignore runtime exceptions.

For errors that may occur during method operation, Java allows the method not to make any throw declaration when the running method does not want to catch. Because most error exceptions belong to situations that can never be allowed to occur, and they are exceptions that reasonable applications should not catch.

For all verifiable exceptions, Java stipulates that a method must catch or declare that it is outside the thrown method. That is, when a method chooses not to catch a traceable exception, it must declare that it will throw an exception.

The method that can catch exceptions needs to provide an exception handler of the corresponding type. The caught exception may be an exception thrown by its own statement, or an exception thrown by a called method or Java runtime system. In other words, the exception that a method can catch must be the exception thrown by java code somewhere. In short, exceptions are always thrown first and then caught.

Any Java code can throw exceptions, such as code written by itself, code from Java development environment package, or Java runtime system. Anyone can throw an exception through Java's throw statement.

Any exception thrown from a method must use the throws clause.

Catch exceptions through try catch statements or try catch finally statements.

Generally speaking, Java stipulates that for verifiable exceptions, they must be caught, declared or thrown. It is allowed to ignore non traceable runtimeException and error.

3.1 catch exceptions: try, catch and finally

1. Try catch statement

In Java, exceptions are caught by a try catch statement. Its general grammatical form is:

A pair of braces after the keyword try packages a piece of code that may have exceptions, which is called the monitoring area. If an exception occurs during the running of a Java method, an exception object is created. Throw the exception out of the monitoring area, and the Java runtime system tries to find a matching catch clause to catch the exception. If there is a matching catch clause, run its exception handling code and the try catch statement ends.

The matching principle is: if the thrown exception object belongs to the exception class of the catch clause or a subclass of the exception class, the generated exception object is considered to match the exception type captured by the catch block.

Example 1: catch the "divisor 0" exception thrown by the throw statement.

Running result: the program has an exception, and the variable B cannot be 0.

The program ends normally.

Example 1 in the try monitoring area, judge through the if statement. When the error condition of "divisor 0" is true, an arithmeticexception exception is raised, an arithmeticexception exception object is created, and the throw statement throws the exception to the Java runtime system. The system finds the matching exception handler catch and runs the corresponding exception handling code, Printout "program exception, variable B cannot be 0." The try catch statement ends and the program flow continues.

In fact, arithmeticexceptions such as "divisor 0" are subclasses of runtimexception. The runtime exception will be thrown automatically by the runtime system without using the throw statement.

Example 2 catch the arithmeticexception exception caused by "divisor is 0" automatically thrown by the system at runtime.

Running result: the program has an exception, and the variable B cannot be 0.

The program ends normally.

Statement in example 2:

"Divisor 0" error occurred during operation, throwing arithmeticexception exception. The runtime system creates an exception object and throws a monitoring area, matches the appropriate exception handler catch, and executes the corresponding exception handling code.

Since the cost of checking runtime exceptions is far greater than the benefits of catching exceptions, runtime exceptions are not available. The java compiler allows you to ignore runtime exceptions. A method can neither catch nor declare to throw runtime exceptions.

Example 3 does not catch or declare to throw runtime exceptions.

Operation results:

Exception in thread "main" java. lang.ArithmeticException: / by zero at Test. TestException. main(TestException.java:8)

Example 4 the program may have the exception of divisor 0 and array subscript out of bounds.

Operation results:

intArray[0] = 0

Value of intarray [0] modulo-2: 0

intArray[1] = 1

Intarray [1] value of modulo-1: 0

intArray[2] = 2

Exception with divisor 0.

The program ends normally.

Example 5 the program may have an exception with a divisor of 0 and an array subscript out of bounds. During the program running, the arithmeticexception exception type is matched first, so execute the matching catch statement:

It should be noted that once a catch catches a matching exception type, it will enter the exception handling code. Once the processing ends, it means that the whole try catch statement ends. Other catch clauses no longer have the opportunity to match and catch exception types.

Java describes exception types through exception classes. The hierarchy of exception classes is shown in Figure 1. For an exception program with multiple catch clauses, the catch clause that captures the underlying exception class should be placed in front of it as much as possible, and the catch clause that captures the relatively high-level exception class should be placed behind it as much as possible. Otherwise, the catch clause that catches the underlying exception class may be masked.

The runtimeException exception class includes various common exceptions at runtime. Arithmeticexception class and ArrayIndexOutOfBoundsException class are its subclasses. Therefore, the catch clause of the runtimeException exception exception class should be placed at the end, otherwise it may mask the subsequent specific exception handling or cause compilation errors.

2. Try catch finally statement

The try catch statement can also include a third part, the finally clause. It represents what should be executed whether or not an exception occurs. The general syntax of the try catch finally statement is:

Example 6 exception handler with finally clause.

Operation results:

Hello world !

--------------------------

Hello World !!

--------------------------

HELLO WORLD !!!

--------------------------

Array subscript out of bounds exception

--------------------------

In example 6, pay special attention to the design of the statement block in the try clause. If the design is as follows, an endless loop will appear. If the design is:

Summary:

Try block: used to catch exceptions. It can be followed by zero or more catch blocks. If there is no catch block, it must be followed by a finally block.

Catch block: used to handle exceptions caught by try.

Finally block: the statements in the finally block will be executed whether or not exceptions are caught or handled. When a return statement is encountered in a try or catch block, the finally statement block will

Is executed before the method returns. Finally blocks will not be executed in the following four special cases:

1) An exception occurred in a finally statement block.

2) System. Is used in the previous code Exit() exits the program.

3) The thread on which the program is located dies.

4) Turn off the CPU.

3. Try catch finally rule (syntax rule of exception handling statement):

1) A catch or finally block must be added after the try. Try blocks can be followed by catch and finally blocks at the same time, but there is at least one block.

2) Block order must be followed: if code uses both catch and finally blocks, catch block must be placed after try block.

3) The catch block is related to the type of the corresponding exception class.

4) A try block may have multiple catch blocks. If so, the first matching block is executed. That is, the Java virtual opportunity matches the exception objects actually thrown with the exception types declared by each catch code block in turn. If the exception object is an instance of an exception type or its subclass, this catch code block will be executed and no other catch code blocks will be executed

5) Try catch finally structures can be nested.

6) In the try catch finally structure, the exception can be thrown again.

7) In addition to the following cases, the execution of finally is always taken as the end: the JVM terminates prematurely (calling system. Exit (int)); Throw an unhandled exception in the finally block; The computer is powered off, on fire, or attacked by a virus.

4. Execution sequence of try, catch and finally statement blocks:

1) When try does not catch exceptions: the statements in the try statement block are executed one by one, and the program will skip the catch statement block and execute the finally statement block and subsequent statements;

2) When an exception is caught in a try, the exception is not handled in the catch statement block: when an exception occurs in a statement in the try statement block, but the catch statement block that handles the exception is not handled, the exception will be thrown to the JVM for processing. The statements in the finally statement block will still be executed, but the statements after the finally statement block will not be executed;

3) When an exception is caught in a try, the exception is handled in the catch statement block: it is executed in order in the try statement block. When an exception occurs in the execution of a certain statement, the program will jump to the catch statement block and match with the catch statement block one by one to find the corresponding processing program. Other catch statement blocks will not be executed, but in the try statement block, The statements after exceptions will not be executed. After the catch statement block is executed, the statements in the finally statement block will be executed, and finally the statements after the finally statement block will be executed;

Illustrates the execution of try, catch and finally statement blocks:

Figure 2 illustrates the execution of try, catch, and finally statement blocks

3.2 throw exception

Any Java code can throw exceptions, such as code written by itself, code from Java development environment package, or Java runtime system. Anyone can throw an exception through Java's throw statement. Any exception thrown from a method must use the throws clause.

1. Throws throws an exception

If a method may have an exception, but it is unable to handle such an exception, you can declare and throw an exception with the throws clause in the method declaration. For example, when the car is running, there may be a fault. If the car itself can't handle the fault, let the driver handle it.

Throws statement is used to declare the exception type to be thrown by the method when defining the method. If the exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated by commas. The syntax format of throws statement is:

Throws exception1,... After the method name, Exceptionn is the list of exceptions declared to be thrown. When a method throws an exception from the exception list, the method will not handle the exceptions of these types and their subclasses, but will throw it to the method calling the method for processing. For example:

After throwing the exception to the caller using the throws keyword, if the caller does not want to handle the exception, he can continue to throw it up, but finally there must be a caller who can handle the exception.

The pop method does not handle the exception negativearraysizeexception, but is handled by the main function.

Rules for throws exception:

1) If it is an unchecked exception, that is, error, runtimeException or their subclasses, you can declare the exception to be thrown without using the throws keyword. The compilation can still pass smoothly, but it will be thrown by the system at run time.

2) Any checked exception that can be thrown by a method must be declared. That is, if a method may have a checked exception, either catch it with a try catch statement or throw it with a throw clause declaration, otherwise it will cause a compilation error

3) Only when an exception is thrown must the caller of the method handle or re throw the exception. When the caller of a method is unable to handle the exception, it should continue to throw it instead of swallowing it.

4) The calling method must follow the handling and declaration rules of any observable exception. If you override a method, you cannot declare an exception different from the override method. Any exception declared must be the same or subclass of the exception declared by the overridden method.

For example:

The basis for judging that a method may be abnormal is as follows:

1) Method has a throw statement. For example, the catch code block of the method7 () method above has a throw statement.

2) Other methods are called, and other methods throw some kind of exception with the throw clause declaration. For example, the method3 () method calls the method1 () method, and the method1 () method declares to throw IOException. Therefore, IOException may occur in the method3 () method.

2. Throw an exception using throw

Throw always appears in the function body to throw an exception of throwable type. The program will terminate immediately after the throw statement, and the statements behind it cannot be executed, and then look for the try block containing the matching catch clause from the inside out in all the try blocks containing it (possibly in the upper calling function).

We know that an exception is an instance object of an exception class. We can create an instance object of an exception class and throw it through a throw statement. The syntax format of this statement is:

For example, throw an exception object of IOException class:

Note that throw can only throw instance objects of the class throwable or its subclasses. The following operation is wrong:

This is because string is not a subclass of throwable class.

If a check exception is thrown, you should also declare the type of exception that the method may throw in the method header. The caller of the method must also check and handle the exception thrown. If all methods throw the obtained exceptions layer by layer, the JVM will handle them in the end. The processing is also very simple, that is, print the exception message and stack information. If an error or runtimeException is thrown, the caller of the method can choose to handle the exception.

3.3 abnormal chain

1) If quotient (3, - 1) is called, myexception will occur, and the program will be transferred to the catch (myexception E) code block for execution;

2) If quotient (5,0) is called, an arithmetexception exception will be raised due to the "divisor is 0" error. It belongs to the runtime exception class and is automatically thrown by the Java runtime system. The quotient () method does not catch the arithmeticexception exception. The Java runtime system will look up the main method along the method call stack and upload the thrown exception to the caller of the quotient () method:

Because the statement is in the try monitoring area, the returned arithmeticexception exception with "divisor 0" is thrown by the Java runtime system and matches the catch clause:

The processing result is that the output "divisor cannot be 0". Java, a processing mechanism that transfers exception information upward, forms an exception chain.

The checked exceptions thrown by Java methods will be passed along the hierarchy of method calls to the calling method with processing ability according to the call stack, and the highest level will be up to the main method. If an exception is passed to the main method, and main does not have the processing capability and does not throw the exception through the throws declaration, a compilation error may occur.

3) If there are other exceptions, catch (exception E) will be used to catch the exception. Because exception is the parent class of all exception classes, if the catch (exception E) code block is placed in front of the other two code blocks, the subsequent code blocks will never be executed, which is meaningless. Therefore, the order of catch statements cannot be reversed.

3.4 common methods in throwable class

Note: the exception type parameter in parentheses after the catch keyword e. Exception is the variable type passed from the try code block to the catch code block, and E is the variable name. Statement "e.getmessage();" in catch code block Used to output the nature of the error. Generally, exception handling uses three functions to obtain information about exceptions:

Getcause(): returns the reason for throwing the exception. Null if cause does not exist or is unknown.

Getmeage(): returns the message information of the exception.

Printstacktrace(): the stack trace of the object is output to the error output stream as the field system The value of err.

Sometimes the code behind the catch statement is ignored for simplicity, so the try catch statement becomes a decoration. Once an exception occurs in the running process of the program, the exception handling will be ignored, and the cause of the error is difficult to find.

5. Common Java exceptions

Some exceptions are provided in Java to describe common errors. Some of these exceptions need to be captured or thrown by programmers, and some are automatically captured and processed by Java virtual machine. Common exception classes in Java:

1. RuntimeException subclass:

1、 java. lang.Arrayindexoutofboundsexception

Array index out of bounds exception. Thrown when the index value of the array is negative or greater than or equal to the array size.

2、java. lang.ArithmeticException

Arithmetic condition exception. For example: integer division by zero, etc.

3、java. lang.NullPointerException

Null pointer exception. This exception is thrown when an application attempts to use null where an object is required. For example, call the instance method of null object, access the properties of null object, calculate the length of null object, throw null with throw statement, etc

4、java. lang.ClassNotFoundException

Class exception not found. This exception is thrown when the application attempts to construct a class according to the class name in string form, but cannot find the class file with the corresponding name after traversing the classpath.

5、java. Lang.negativearraysizeexception array length is negative exception

6、java. The lang.arraystoreexception array contains an exception thrown by incompatible values

7、java. Lang.securityexception security exception

8、java. Lang.illegalargumentexception illegal parameter exception

2.IOException

IOException: an exception that may occur when manipulating input and output streams.

Eofexception file ended exception

FileNotFoundException file found no exception

3. Others

ClassCastException type conversion exception class

The arraystoreexception array contains an exception thrown by incompatible values

Sqlexception operation database exception class

Nosuchfieldexception field found no exception

The nosuchmethodexception method did not find the exception thrown

Numberformatexception an exception thrown when a string is converted to a number

Stringindexoutofboundsexception exception thrown when the string index is out of range

Allegalaccessexception does not allow access to certain types of exceptions

Instantiationexception this exception is thrown when the application attempts to create an instance of a class using the newinstance () method in the class class, and the specified class object cannot be instantiated

6. Custom exception

Using Java's built-in exception class can describe most exceptions during programming. In addition, users can customize exceptions. You can customize the exception class by inheriting the exception class.

Using custom exception classes in programs can be roughly divided into the following steps.

(1) Create a custom exception class.

(2) Throw an exception object through the throw keyword in the method.

(3) If the exception is handled in the method that currently throws the exception, you can use the try catch statement to catch and handle it; otherwise, indicate the exception to be thrown to the method caller through the throws keyword in the method declaration, and continue to the next step.

(4) Catch and handle exceptions in the caller of the exception method.

The above example of "throwing an exception using throw" has already been mentioned.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>