Thinking logic of computer programs (25), thinking Logic
In the previous section, we introduced the basic concepts and classes of exceptions. In this section, we will further introduce how to handle exceptions. Let's first look at Java's support for exception handling, then we will discuss how to handle exceptions in practice.
Exception Handling
Catch match
The previous section briefly introduced how to use try/catch to catch exceptions. There is only one catch. In fact, there can be multiple catch entries, each of which corresponds to one exception type, for example:
Try {// code that may trigger an exception} catch (NumberFormatException e) {System. out. println ("not valid number");} catch (RuntimeException e) {System. out. println ("runtime exception" + e. getMessage ();} catch (Exception e) {e. printStackTrace ();}
The exception handling mechanism will find the First Matching catch Block Based on the thrown exception type. After the block is found, the code in the catch block will be executed. Other catch blocks will not be executed. If not, will continue to the upper method to find. Note that the Exception type thrown is that the subclass that declares the Exception in catch is also matched, so you need to put the most specific subclass in front. If the base class Exception is placed in front, other more specific catch code will not be executed.
The example also demonstrates the use of exception information. e. getMessage () gets the exception message, and e. printStackTrace () prints the exception stack to the standard error output stream. This information helps you understand why exceptions occur, which is a common solution to programming errors. The example is to directly output the information to the standard stream. A more common practice in the actual system is to output the information to a dedicated log.
Throw again
After the catch Block is processed, you can throw an exception again. The exception can be the original one or the new one, as shown below:
Try {// code that may trigger an exception} catch (NumberFormatException e) {System. out. println ("not valid number"); throw new AppException ("incorrect input format", e);} catch (Exception e) {e. printStackTrace (); throw e ;}
For an Exception, it is thrown again through throw e after the Exception stack is printed.
For NumberFormatException, we throw an AppException again. The current Exception is passed to AppException as a cause, which forms an Exception chain. The code that captures AppException can use getCause () obtain NumberFormatException.
Why should I throw it again? Because the current Code cannot completely handle this exception, the caller needs to further handle it.
Why should we throw a new exception? Of course, the current exception is not suitable. inappropriate information may be insufficient. Some new information needs to be added. It may be too detailed for the caller to understand and use it. If the caller is interested in details, you can continue to get the original exception through getCause.
Finally
An important part of the exception mechanism is finally. catch can be followed by finally statements. The syntax is as follows:
Try {// an Exception may be thrown} catch (Exception e) {// catch an Exception} finally {// execute the command regardless of the Exception}
Code in finally is executed regardless of whether an exception occurs. Specifically:
- If no exception occurs, execute the code in the try.
- If an exception occurs and is caught by a catch, it is executed after the code in the catch is executed.
- If an exception occurs but is not captured, it is executed before the exception is thrown to the upper layer.
Finally is used to release resources, such as database connections and file streams.
In try/catch/finally syntax, catch is not required, that is, it can only be try/finally, indicating that no exception is caught and the exception is automatically passed up, however, the finally code is also executed after an exception occurs.
The finally statement has an execution detail. If a return statement exists in a try or catch statement, the return Statement is executed only after the finally statement is executed, but the finally statement cannot change the return value, let's take a look at the Code:
public static int test(){ int ret = 0; try{ return ret; }finally{ ret = 2; }}
The return value of this function is 0 rather than 2. The actual execution process is to save the returned value ret in a temporary variable before the return ret statement is executed in try, then execute the finally statement, and then try to return the temporary variable. The modification to ret in finally will not be returned.
What if there is a return statement in finally? The return value in try and catch is lost, and the return value in finally is actually returned. In finally, return not only overwrites the return values in try and catch, but also masks exceptions in try and catch, just as if the exception did not occur. For example:
public static int test(){ int ret = 0; try{ int a = 5/0; return ret; }finally{ return 2; }}
In the above Code, 5/0 will trigger ArithmeticException, but in finally there is a return statement, this method will return 2, instead of passing an exception up.
In finally, not only the return statement will mask the exception, but if an exception is thrown in finally, the original exception will be masked. See the following code:
public static void test(){ try{ int a = 5/0; }finally{ throw new RuntimeException("hello"); }}
If a RuntimeException is thrown in finally, the original ArithmeticException is lost.
Therefore, to avoid confusion, you should avoid using the return statement or throwing an exception in finally. If other code called may throw an exception, you should capture the exception and handle it.
Throws
In the exception mechanism, there is also a keyword throws, which is similar to throw, used to declare an exception that a method may throw. The syntax is as follows:
public void test() throws AppException, SQLException, NumberFormatException { //....}
Throws follows the brackets of the method. Multiple exceptions can be declared and separated by commas. The meaning of this statement is that I may throw these exceptions in this method. I have not processed them, at least not finished. The caller must handle them. This statement does not explain what exceptions will be thrown in specific situations. As a good practice, the information should be described in comments so that the caller can better handle exceptions.
For RuntimeException (unchecked exception), throws is not required for declaration, but for checked exception, it must be declared. In other words, if no declaration is made, it cannot be thrown.
For a checked exception, it cannot be thrown but not declared, but can be declared to be thrown but not actually thrown. What should I do if I don't throw it? It is mainly used to declare in the parent class method. The parent class method may not be thrown, but it may be thrown after the subclass rewrite method. The subclass cannot throw a checked exception that is not declared in the parent class method, therefore, all possible exceptions are written to the parent class.
If one method calls another method that declares that the checked exception is thrown, the checked exception must be handled. However, the method can be catch or continue to use throws, the following code is used:
public void tester() throws AppException { try { test(); } catch (SQLException e) { e.printStackTrace(); }}
For SQLException thrown by test, catch is used here. For AppException, it is added to the throws statement of its own method, indicating that the current method cannot be processed either. It should be processed by the upper layer.
Checked compared with Unchecked Exception
The preceding figure shows the difference between RuntimeException (unchecked exception) and checked exception. The checked exception must appear in the throws statement, and must be handled by the caller. the Java compiler enforces this, runtimeException does not have this requirement.
Why is there a distinction? Should we use checked or unchecked exception when defining exceptions? There are various opinions and arguments in the industry regarding this issue, and there is no particularly consistent conclusion.
A common saying is that RuntimeException (unchecked) indicates a logic error in programming. Check it during programming to avoid these errors, such as null pointer exceptions. If these exceptions occur, program exit is also normal, the programmer should check the program code bug rather than trying to handle this exception. Checked exception indicates that the program itself is normal, but the caller should handle exceptions caused by I/O, network, database and other unpredictable errors.
But in fact, programming errors should also be handled. In particular, Java is widely used in server programs and cannot exit the program due to a logic error. Therefore, this distinction in Java is of little significance and can be replaced by RuntimeException (unchcked exception.
The basic reason for this is that, whether it is a checked or unchecked exception, whether or not it appears in the throws Declaration, we should handle it in the appropriate way, instead of blindly handling exceptions to meet the requirements of the compiler, the mandatory declaration and processing of checked exceptions are too long, especially when the call level is deep.
In fact, the viewpoint itself is not very important, and more importantly, consistency. In a project, an agreement should be reached on how to use exceptions, just as agreed. The existing exceptions and class libraries in Java are also in place. We still need to use them according to their requirements.
How to use exceptions
For exceptions, we have introduced try/catch/finally, catch matching, re-throwing, throws, checked/unchecked exception. How should we use exceptions?
Exceptions should be used only for exceptions
This means that exceptions cannot be used as normal conditions. For example, when processing array elements in a loop, you should first check whether the index is valid before processing, instead of waiting to throw an index exception and then end the loop. For a referenced variable, if its value may also be null under normal circumstances, check whether it is null or not before calling it.
On the other hand, when an exception occurs, an exception should be thrown instead of returning a special value. For example, let's look at the String substring method, which returns a substring. Its code is as follows:
public String substring(int beginIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } int subLen = value.length - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);}
The code checks the validity of beginIndex. If it is invalid, StringIndexOutOfBoundsException is thrown. A possible alternative to pure technology is to return a special null value without throwing an exception, but invalid beginIndex is an exception. Exceptions cannot be pretended to be handled normally.
Exception Handling Objectives
Exceptions can be divided into three sources: users, programmers, and third parties. Users mean that user input is incorrect, programmers mean programming errors, and third parties generally refer to other situations such as I/O errors, networks, databases, and third-party services. Each exception should be properly handled.
The targets can be classified into reports and recovery. Recovery means that the problem is automatically solved through the program. The report may end with users, namely program users, system O & M personnel or programmers. The purpose of the report is to recover, but the recovery often requires human participation.
If the user input is incorrect, the user may be prompted where the user entered the wrong information. If it is a programming error, the user may be prompted a system error. We suggest you contact customer service. If it is a third-party connection problem, you may be prompted to try again later.
For system O & M personnel or programmers, they generally do not care about user input errors, but focus on programming errors or third-party errors. For these errors, the report should be as complete as possible, including exception chains and exception stacks to locate and solve problems as soon as possible.
For user input or programming errors, it is generally difficult to automatically solve through the program, third-party errors may be possible, and in many cases, the program should not assume that the third party is reliable, there should be a fault tolerance mechanism. For example, if a third-party service cannot be connected (for example, a text message), the possible fault tolerance mechanism is to try another third party that provides the same function. It may also be that retry at intervals, report an error after multiple failures.
General Exception Handling Logic
If you know how to handle the exception, you can handle it. If you can solve the exception automatically through the program, it will be automatically resolved. If the exception can be resolved by yourself, you do not need to report it to the user.
If you cannot solve the problem, report the problem to Alibaba Cloud. If you have additional information to help you analyze and solve the problem, you should provide it. You can use the original exception as cause to throw an exception again.
There is always a layer of code that is responsible for exceptions. It may be the code that knows how to handle the exception, it may be the code of the user or the main program. If the exception cannot be automatically solved, users should provide information that users can understand and help users based on the exception information, for O & M and programmers, the detailed exception trace and exception stack should be output to the log.
This logic is similar to the logic for handling problems in the company. Each level has its own problem to be resolved. If it can be handled by itself, it should be reported to its superiors if it cannot be handled, tell him what his subordinates told him and what he knows. In the end, the company boss must be responsible for all problems. Each level should neither cover up the problem nor escape responsibility.
Summary
This section describes the exception mechanism in Java. In the absence of an exception mechanism, the only exit mechanism is return. The method to determine whether an exception is returned is used.
The method returns different return values based on the exception or not. The caller determines and processes the returned values accordingly. Each method layer needs to check and process each different return value of the called method. The normal logic of the program is mixed with the exception logic, and the code is often hard to read, understand, and maintain.
In addition, exceptions are rare, and programmers are often lazy. If exceptions do not occur, they ignore the check on the return values of exceptions, reducing program reliability.
With the exception mechanism, the normal logic of the program can be separated from the exception logic, and the exception can be processed in a centralized manner. Exceptions can also be automatically passed up without processing each layer of methods, exceptions can no longer be automatically ignored. Therefore, codes that handle exceptions can be greatly reduced, and the code readability, reliability, and maintainability can also be improved.
So far, we have introduced the main concepts of the Java language. In the following sections, we will introduce some common classes and their operations in Java, starting with the packaging class.
----------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Write with your heart, original articles, and retain all copyrights.
-----------
More original articles
Thinking logic of computer programs (1)-data and variables
Thinking logic of computer programs (5)-Why is an error in decimal calculation?
Thinking logic of computer programs (6)-How to recover from garbled code (I )?
Thinking logic of computer programs (8)-true meaning of char
Thinking logic of computer programs (12)-Basic Principles of function calls
Thinking logic of computer programs (17)-Basic Principle of inheritance implementation
Thinking logic of computer programs (18)-Why inheritance is a double-edged sword
Thinking logic of computer programs (19)-essence of interfaces
Thinking logic of computer programs (20)-Why abstract classes?
Thinking logic of computer programs (21)-nature of internal classes
Thinking logic of computer programs (23)-nature of enumeration
Thinking logic of computer programs (24)-exception (I)