Home  >  Article  >  Java  >  What is java exception? How are java exceptions handled?

What is java exception? How are java exceptions handled?

青灯夜游
青灯夜游forward
2018-10-19 18:01:445078browse

The content of this article is to introduce to you what is java exception? How are java exceptions handled? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. JAVA exception

Exception refers to various unexpected situations, such as: file not found, network connection failure , illegal parameters, etc. An exception is an event that occurs during program execution and interferes with the normal flow of instructions. Java describes various exceptions through numerous subclasses of the Throwable class in the API. Therefore, Java exceptions are objects, instances of Throwable subclasses, that describe error conditions that occur in a piece of coding. Error will throw an exception when the condition is generated.

Java exception class hierarchy diagram:

What is java exception? How are java exceptions handled?

Throwable: There are two Two important subclasses: Exception and Error, both are important subclasses of Java exception handling, and each contains a large number of subclasses.

Error: is an error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with actions performed by the code writer and instead represent problems with the JVM (Java Virtual Machine) while the code is running. For example, Java virtual machine running error (Virtual MachineError), when the JVM no longer has the memory resources required to continue executing the operation, an OutOfMemoryError will occur. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread.

Exception: is an exception that the program itself can handle.

Java exceptions (including Exception and Error) are divided into checkable exceptions (checked exceptions) and unchecked exceptions (unchecked exceptions) .

Checkable exceptions (exceptions that the compiler requires to be handled): exceptions that are easy to occur and are tolerable when a correct program is running. Although checkable exceptions are abnormal situations, their occurrence can be expected to a certain extent, and once such abnormal situations occur, they must be handled in some way.

Except RuntimeException and its subclasses, other Exception classes and their subclasses are checkable exceptions. The characteristic of this kind of exception is that the Java compiler will check it. That is to say, when this kind of exception may occur in the program, either use the try-catch statement to capture it, or use the throws clause to declare it, otherwise the compiler Will not pass.

Uncheckable exceptions (exceptions that the compiler does not require forced handling): include runtime exceptions (RuntimeException and its subclasses) and errors (Error).

Note: Exceptions can be handled by the program itself, but errors cannot be handled.

#Exception This exception is divided into two major categories: runtime exceptions and non-runtime exceptions (compilation exceptions). The program should handle these exceptions as much as possible.

Runtime exceptions: are exceptions of the RuntimeException class and its subclasses, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript Out-of-bounds exceptions), etc. These exceptions are unchecked exceptions. You can choose to capture them in the program or not handle them. These exceptions are generally caused by program logic errors, and the program should try to avoid the occurrence of such exceptions from a logical perspective.

The characteristic of runtime exceptions is that the Java compiler will not check it. That is to say, when this type of exception may occur in the program, even if it is not captured with a try-catch statement, it is not declared with a throws clause. Throw it and it will compile.

Non-runtime exception (compilation exception): is an exception other than RuntimeException, and all types belong to the 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 will not be compiled. Such as IOException, SQLException, etc. and user-defined Exceptions. Generally, no custom checked exceptions are required.

2. Mechanism for handling exceptions

In Java applications, the exception handling mechanism is: throwing exceptions , catch exceptions.

Throws an exception: When an error occurs in a method and an exception is thrown, the method creates an exception object and delivers it to run In the current system, the exception object contains information such as the exception type and the exception status when the exception occurs. The runtime system is responsible for finding the code to handle the exception and executing it.

Catching exceptions: After the method throws an exception, the runtime system will turn to find a suitable exception handler (exception handler). The potential exception handler is the exception that occurs A collection of methods that remain in the call stack in sequence. When the exception type that the exception handler can handle matches the exception type thrown by the method, it is a suitable exception handler. The runtime system starts from the method where the exception occurred and checks back the methods in the call stack until it finds the method containing the appropriate exception handler and executes it. When the runtime system traverses the call stack and does not find a suitable exception handler, the runtime system terminates. At the same time, it means that the java program terminates.

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

Errors that may occur during method execution. When the running method does not want to catch it, Java allows the method to not make any throwing statement. Because most Error exceptions are situations that should never be allowed to occur and are exceptions that reasonable applications should not catch.

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

Generally speaking, Java stipulates that checkable exceptions must be caught or declared to be thrown. Allows ignoring uncheckable RuntimeException and Error.

3. Catching exceptions: try, catch and finally

##1.try-catch statement

What is java exception? How are java exceptions handled?

A pair of braces after the keyword try Wrapping a piece of code where exceptions may occur is called a monitoring area. If an exception occurs during the running of a Java method, an exception object is created. The exception is thrown outside 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, its exception handling code is run, and the try-catch statement ends. Program execution continues.

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

Do not catch or declare runtime exceptions. The program will throw an exception and end the operation.

What is java exception? How are java exceptions handled?

#Once a catch catches a matching exception type, the exception handling code will be entered. Once the processing is completed, it means that the entire try-catch statement ends. Other catch clauses no longer have the opportunity to match and catch the exception type. You should try to place the catch clauses that capture low-level exception classes at the front, and try to place the catch clauses that capture relatively high-level exception classes at the back. Otherwise, the catch clause that captures the underlying exception class may be blocked.

2.try-catch-finally

The try-catch statement can also include a third part, which is the finally clause. It indicates what should be executed regardless of whether an exception occurs. The general syntax form of the try-catch-finally statement is:

What is java exception? How are java exceptions handled?

try block: is 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: is used to handle exceptions caught by try.

finally block: The statements in the finally block will be executed regardless of whether the exception is caught or handled. When a return statement is encountered in a try block or catch block, the finally statement block will be executed before the method returns. Under the following 4 special circumstances, the finally block will not be executed:

1) An exception occurs in the finally statement block.

2) System.exit() is used in the previous code to exit the program.
3) The thread where the program is located dies.
4) Turn off the CPU.

3. try-catch-finally rules ( Grammar rules for exception handling statements):

#1) A catch or finally block must be added after try. The try block can be followed by both catch and finally blocks, but there must be at least one block.

2) Block order must be followed: If the code uses both catch and finally blocks, the catch block must be placed after the 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 machine will match the exception object actually thrown with the exception type declared in each catch code block in turn. If the exception object is an instance of a certain exception type or its subclass, the catch code block will be executed and no other will be executed. The catch code block

5) The try-catch-finally structure can be nested.

6) In the try-catch-finally structure, exceptions can be re-thrown.
7) Except for the following situations, finally will always be executed as the end: JVM prematurely terminates (calling System.exit(int)); an unhandled exception is thrown in the finally block; the computer is powered off, Fire or virus attack.

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

1) When try does not catch an exception: 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 try An exception is caught and the exception is not handled in the catch statement block: When an exception occurs in a statement in the try statement block and there is no catch statement block to handle the exception, the exception will be thrown to the JVM for processing, finally statement The statements in the block will still be executed, but the statements after the finally statement block will not be executed;

3) When try catches an exception, there is a situation to handle the exception in the catch statement block: in the try statement block are executed in sequence. When an exception occurs when a certain statement is executed, the program will jump to the catch statement block and match the catch statement blocks one by one to find the corresponding handler. Other catch statement blocks will not is executed, and in the try statement block, the statements after the exception will not be executed. After the catch statement block is executed, the statements in the finally statement block are executed, and finally the statements after the finally statement block are executed;

Illustration shows the execution of try, catch and finally statement blocks:

What is java exception? How are java exceptions handled?

##5. Throw exceptions

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

1. throws throws an exception

If a method may cause an exception, but does not have the ability to handle it Exceptions can be declared using the throws clause at the method declaration.

What is java exception? How are java exceptions handled?

The throws Exception1,Exception2,...,ExceptionN after the method name are the list of exceptions to be thrown. When a method throws an exception from the exception list, the method will not handle exceptions of these types and their subclass types, but will be thrown to the method that calls the method for handling.

Throws rules for throwing exceptions:

1) If it is an unchecked exception, that is, Error, RuntimeException or their subclass, then you can declare the exception to be thrown without using the throws keyword. The compilation will still pass smoothly, but it will be thrown by the system at runtime.

2) Any checked exceptions that the method can throw must be declared. That is, if a method may have a checkable exception, either use a try-catch statement to catch it, or use a throws clause statement to throw it, otherwise it will cause a compilation error

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

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

The basis for judging whether an exception may occur in a method is as follows:

1)There is a throw statement in the method.

#2) Other methods are called, and other methods use the throws clause to declare that they throw some kind of exception.

If all methods throw the obtained exception layer by layer, the JVM will eventually process it, and the processing is also very simple, which is to 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.

2. Commonly used methods in the Throwable class

getCause(): Returns the reason for throwing the exception. If cause does not exist or is unknown, null is returned.

getMeage(): Returns the abnormal message information.

printStackTrace(): The object’s stack trace is output to the error output stream as the value of the field System.err.

6. Java common exceptions

Java provides some exceptions to describe frequently occurring errors. For these exceptions, some require programmers Perform capture processing or declare a throw, and some are automatically captured by the Java virtual machine. Common exception classes in Java:

1. runtimeException subclass: (unchecked exception)

  • ## java.lang.ArrayIndexOutOfBoundsException

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

  • java.lang.ArithmeticException

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

  • java.lang.NullPointerException

    Null pointer exception. This exception is thrown when the application attempts to use null where an object is required. For example: calling the instance method of the null object, accessing the properties of the null object, calculating the length of the null object, using the throw statement to throw null, etc.

  • java.lang.ClassNotFoundException

    Find Less than class exception. This exception is thrown when the application attempts to construct a class based on a class name in string form, but cannot find the class file with the corresponding name after traversing the CLASSPAH.

  • java.lang.NegativeArraySizeException The array length is negative.

  • java.lang.ArrayStoreException The array contains incompatible values.

  • java.lang.SecurityException Security exception

2.IOException(checked exception)

IOException: Possible when operating input streams and output streams abnormal.

EOFException File ended exception

FileNotFoundException File not found exception

3. Others

ClassCastException Type conversion exception class

ArrayStoreException Exception thrown when the array contains incompatible values

SQLException Operation database exception class

NoSuchFieldException Field not found exception

NoSuchMethodException The exception thrown by the method not found

NumberFormatException The exception thrown by converting a string to a number

StringIndexOutOfBoundsException The exception thrown by the string index out of range

IllegalAccessException Access not allowed Certain type of exception

InstantiationException This exception is thrown when the application attempts to use the newInstance() method in the Class class to create an instance of a class, but the specified class object cannot be instantiated

4. Custom exceptions

Using Java's built-in exception class can describe most exceptions that occur during programming. In addition, users can also customize exceptions. User-defined exception classes only need to inherit the Exception class.

Using custom exception classes in a program 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 capture and process it; otherwise, use the throws keyword at the declaration of the method to indicate the exception to be thrown to the method caller, and continue Go to the next step.
(4) Catch and handle exceptions in the caller of the exception method.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit

Java video tutorial, java development graphic tutorial, bootstrap video tutorial!

The above is the detailed content of What is java exception? How are java exceptions handled?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact [email protected] delete