exception handling
What is an exception
Although everyone hopes to be healthy and handle things smoothly, they will always encounter various conditions in real life, such as cold and fever, blue screen of computer at work, crash, etc. Similarly, in the process of program operation, various abnormal conditions will also occur, such as insufficient disk space, interrupted network connection and nonexistence of loaded classes. In view of this situation, exceptions are introduced into the Java language to encapsulate these abnormal situations in the form of exception classes, and deal with various problems during program running through exception handling mechanism. Next, let's understand what an exception is through a case, as shown in the example.
public class Example { public static void main(String[] args) { int result = divide(4, 0); // Call the divide() method System.out.println(result); } // The following method implements the division of two integers public static int divide(int x, int y) { int result = x / y; // Define a variable result to record the result of dividing two numbers return result; // Return results } }
Operation results:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Example.divide(Example.java:9) at Example.main(Example.java:3)
It can be seen from the running results that an arithmetic exception occurred in the program. This exception is due to the parameter 0 passed in when the third line of code in the program called the divide() method, and the error of division by 0 occurred in the operation of the eighth line of code in the method. After this exception occurs, the program will end immediately and cannot continue to execute downward.
An ArithmeticException exception is generated in the example. The ArithmeticException exception is only one of the Java exception classes. A large number of exception classes are also provided in Java, which inherit from Java Lang. Throwable class. Next, a diagram is used to show the inheritance system of Throwable class, as shown in the figure.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-4x97mcs1-1642058611503)( http://47.107.171.232/easily-j/images/20190108/87f56d7b-d911-4ade-892c-c392dfc409b6.png )]
As can be seen from the figure, Throwable has two direct subclasses, Error and Exception, in which Error represents the Error generated in the program and Exception represents the Exception generated in the program. Next, we will explain these two direct subclasses in detail.
- Error class
The Error class is called the Error class. It indicates that the system internal Error or resource depletion Error generated by Java runtime is relatively serious, and the execution cannot be resumed only by modifying the program itself. For example, in the process of building, the building collapsed due to Jerry building, which is equivalent to an Error.
- Exception class
Exception class is called exception class. It represents the errors that can be handled by the program itself. Exception handling in developing Java programs is aimed at exception class and its subclasses. Among the many subclasses of exception class, there is a special RuntimeException class. This class and its subclasses are used to represent runtime exceptions. In addition to this class, all other subclasses under exception class are used to represent compile time exceptions. This section mainly explains the exception class and its subclasses.
We have learned about Throwable class through the previous study. In order to facilitate the later study, we will list the common methods in Throwable class, as shown in the table.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qpjkqbwv-1642058611504)( http://47.107.171.232/easily-j/images/20190108/52da4fe8-0876-499e-9e89-99b314e8638f.png )]
These methods in the table are used to obtain Exception information. Since Error and Exception inherit from Throwable class, they both have these methods, and they will gradually contact the use of these methods in the later Exception learning.
try... catch and finally
In the above example, due to an exception, the program terminates immediately and cannot continue to execute downward. In order to solve this problem, Java provides a way to deal with exceptions - exception capture. The try... catch statement is usually used for exception capture. The specific syntax format is as follows:
try{ //Program code block }catch(ExceptionType(Exception Class and its subclasses) e){ //Handling of ExceptionType }
Java statements that may cause exceptions are written in the try code block, and code for handling exceptions is written in the catch code block. When an Exception occurs in the program in the try code block, the system will encapsulate the Exception information into an Exception object and pass the object to the catch code block. Catch code block needs a parameter to indicate the Exception type it can receive. The type of this parameter must be Exception class or its subclass.
Next, use the try... Catch statement to catch the exception in the above example.
public class Example { public static void main(String[] args) { // The following code defines a try... Catch statement to catch exceptions try { int result = divide(4, 0); // Call the divide() method System.out.println(result); } catch (Exception e) { // Handle exceptions System.out.println("The exception information captured is: " + e.getMessage()); } System.out.println("The program continues down"); } // The following method implements the division of two integers public static int divide(int x, int y) { int result = x / y; // Define a variable result to record the result of dividing two numbers return result; // Return results } }
Operation results:
The exception information captured is: / by zero The program continues down
In the example, the code with possible exceptions is processed with the try... Catch statement. If an Exception divided by 0 occurs in the try code block, the program will instead execute the code in catch and return the Exception information "/ byzero" by calling the getMessage() method of the Exception object. After the catch code block handles the Exception, the program will still execute downward without abnormal termination.
In a program, sometimes we want some statements to be executed regardless of whether an exception occurs in the program. At this time, we can add a finally code block after the try... catch statement. Next, modify example 4-22 to demonstrate the usage of finally code block, as shown in the example.
public class Example { public static void main(String[] args) { // The following code defines a try... Catch statement to catch exceptions try { int result = divide(4, 0); // Call the divide() method System.out.println(result); } catch (Exception e) { // Handle exceptions System.out.println("The exception information captured is: " + e.getMessage()); } finally { System.out.println("get into finally Code block"); } System.out.println("The program continues down"); } // The following method implements the division of two integers public static int divide(int x, int y) { int result = x / y; // Define a variable result to record the result of dividing two numbers return result; // Return results } }
Operation results:
The exception information captured is: / by zero get into finally Code block The program continues down
A return statement is added to the catch code block to end the current method. At this time, the code on line 12 of the program will not be executed, but the code in finally will still be executed and will not be affected by the return statement. That is to say, whether the program is abnormal or ends with a return statement, the statements in finally will be executed. It is precisely because of this particularity, In programming, we often use the finally code block after try... Catch to complete the things that must be done, such as releasing system resources.
It should be noted that in one case, the code block in finally will not be executed, that is, the system. Net is executed in try... catch Exit (0) statement. System.exit(0) means to exit the current Java virtual machine. The Java virtual machine stops and no code can be executed.
throws keyword
In the previous example, since the divide() method written by yourself is called, it is clear that exceptions may occur in this method. Just think, if you call a method written by others, can you know whether there will be exceptions in the method written by others? It's hard to judge. In view of this situation, Java allows you to use the throws keyword behind the method to declare the possible exceptions of the method, so that when calling the method, the caller will clearly know that the method has exceptions, and must handle the exceptions in the program, otherwise the compilation cannot pass.
throws keyword declares that the syntax format of throwing an exception is as follows:
Modifier return value type method name([Parameter 1, parameter 2])throws ExceptionType1[,ExceptionType2...]{ }
It can be seen from the above syntax format that the throws keyword needs to be written after the method declaration, and the type of exception in the method needs to be declared after the throws. This practice is usually called method declaration throwing an exception. Then use the same try catch structure to throw an exception to ensure that the program will not terminate during execution. Next, modify the example and declare the exception thrown on the devide() method, as shown in the example.
public class Example { public static void main(String[] args) { // The following code defines a try... Catch statement to catch exceptions try { int result = divide(4, 2); // Call the divide() method System.out.println(result); } catch (Exception e) { // Handle the caught exception e.printStackTrace(); // Print captured exception information } } // The following method divides two integers and uses the throws keyword declaration to throw an exception public static int divide(int x, int y) throws Exception { int result = x / y; // Define a variable result to record the result of dividing two numbers return result; // Return results } }
Operation results:
2
Runtime and compile time exceptions
In actual development, some exceptions are often generated during program compilation, and these exceptions must be handled. This exception is called compile time exception, also known as checked exception. In addition, there is an exception that occurs when the program is running. Even if the exception handling code is not written, it can still be compiled. Therefore, it is called runtime exception, also known as unchecked exception. Next, we will explain these two exceptions in detail.
Compile time exception
In Java, Exception classes are compile time exceptions except RuntimeException class and its subclasses. The feature of compile time Exception is that the java compiler will check it. If there is an Exception, the Exception must be handled, otherwise the program cannot pass compilation.
There are two ways to handle exceptions during compilation, as follows:
-
Use the try... Catch statement to catch exceptions.
-
Use the throws keyword to declare that an exception is thrown and the caller handles it.
Runtime exception
The RuntimeException class and its subclasses are runtime exceptions. The characteristic of runtime exceptions is that the Java compiler will not check them, that is, when such exceptions occur in the program, the program can be compiled even if it is not caught by the try... catch statement or thrown by the throw keyword declaration. Run time exceptions are generally caused by logical errors in the program and cannot be recovered when the program is running. For example, if the maximum angle of the array is exceeded when accessing the elements of the array through the angle of the array, a runtime exception will occur. The code is as follows:
int [] arr = new int[5]; System.out.println(arr[6]);
In the above code, since the length of array arr is 5, the maximum subscript should be 4. When using arr[6] to access the elements in the array, the array subscript will be out of bounds.
Custom exception
A large number of Exception classes are defined in the JDK. Although these Exception classes can describe most of the exceptions during programming, it may be necessary to describe the unique exceptions in the program during program development. For example, when designing the divide() method, the divisor is not allowed to be negative. To solve this problem, users are allowed to customize exceptions in Java, but the custom Exception class must inherit from Exception or its subclasses. Next, learn through a case, as shown in the example.
//The following code is to customize an Exception class, which inherits from Exception public class DivideByMinusException extends Exception { public DivideByMinusException() { super(); // Call Exception parameterless constructor } public DivideByMinusException(String message) { super(message); // Call the constructor with Exception parameters } }
In actual development, if there are no special requirements, the custom Exception class only needs to inherit the Exception class, and use the super() statement in the construction method to call the construction method of Exception.
Since the exception is customized, how to use it? In this case, the throw keyword is needed. The throw keyword is used to declare the instance object that throws an exception in the method. Its syntax format is as follows:
throw Exception Exception object
Next, rewrite the divide() method in the above example where the divisor is 0. Judge whether the divisor is negative in the divide() method. If it is negative, use the throw keyword to throw a custom DivideByMinusException exception exception object to the caller in the method, as shown in the example.
public class Example { public static void main(String[] args) { // The following code defines a try... Catch statement to catch exceptions try { // Call the divide() method and pass in a negative number as the divisor int result = divide(4, -2); System.out.println(result); } catch (DivideByMinusException e) { // Handle the caught exception System.out.println(e.getMessage()); // Print captured exception information } } // The following method divides two integers and throws a custom exception using the throws keyword declaration public static int divide(int x, int y) throws DivideByMinusException { if (y < 0) { // Declare an exception object using the throw keyword throw new DivideByMinusException("The divisor is negative"); } int result = x / y; // Define a variable result to record the result of dividing two numbers return result; // Return results } }
Operation results:
The divisor is negative
In the main() method of the example, a try... Catch statement is defined to catch the exception thrown by the divide() method. When calling the divide() method, because the passed divisor cannot be negative, the program will throw a custom exception DivideByMinusException. After the exception is caught, it will be processed by the catch code block and the exception information will be printed.