In programming, exception handling is a very critical and important part. The exception-handling framework of a program directly affects the quality of the entire project and the cost and difficulty of subsequent maintenance. Imagine if a project did not consider exception handling from beginning to end, and where did the program go wrong to find the source of the error? However, if a project has too many design exceptions, it can seriously affect the quality of the code and the performance of the program. Therefore, how to design exception handling efficiently and concisely is an art, this article first describes the Java anomaly mechanism of the most basic knowledge, and then gives in the Java exception processing design when a few suggestions.
If there is a point, please forgive and correct, I appreciate it.
Please respect the author's labor results, reproduced please indicate the reprint address: http://www.cnblogs.com/dolphin0520/p/3769804.html
The following is the directory outline for this article:
I. What is an exception
Two. How exceptions are handled in Java
Three. Deep understanding of Try,catch,finally,throws,throw Five keywords
Four. When the class inherits, how to make the exception throw declaration when the method overrides
Five. Several recommendations for exception handling and design
I. What is an exception
Abnormal English words are exception, literal translation is the meaning of "accident, exception", that is, abnormal situation. In fact, exceptions are procedural errors in nature, including procedural logic errors and system errors. For example, the use of empty references, array subscript out of bounds, memory overflow errors, and so on, these are unexpected circumstances, deviating from the intentions of our program itself. Errors occur frequently during the process of writing a program, including errors during compilation and during run time, errors that occur during compilation are compiled to help us fix it, but errors during runtime are not what the compiler can do, and errors during runtime are often unpredictable. If an error occurs while the program is running, if it is ignored, the program terminates or directly causes the system to crash, obviously this is not the result we want to see. So how do you handle and remediate errors that occur during a run? Java provides an exception mechanism to handle errors that occur during program operation through an exception mechanism. With the exception mechanism, we can better improve the robustness of the program.
Exceptions are handled as objects in Java, the root class is the Java.lang.Throwable class, and many exception classes are defined in Java (such as OutOfMemoryError, NullPointerException, Indexoutofboundsexception, etc.), these exception classes fall into two main categories: Error and exception.
Error is an unhandled exception, such as OutOfMemoryError, which typically occurs, and the JVM chooses to terminate the program. So we don't need to be concerned with this kind of exception when we write programs.
Exception, which is something we often see, such as NullPointerException, indexoutofboundsexception, are exceptions that we can handle.
Exceptions to the exception class include checked exception and unchecked exception (unchecked exception also known as Run-time exception runtimeexception, Of course, the run-time exception here is not the exception that I described earlier in the run, but the term "runtime exception" is used in Java to indicate that the exception of the exception class occurs during runtime.
Unchecked Exception (non-check exception), also known as Run-time exceptions (runtimeexception), such as Common NullPointerException, indexoutofboundsexception. For run-time exceptions, the Java compiler does not require exception capture processing or claims to be thrown, which is the programmer's discretion.
Checked exception (check for exceptions), also known as non-runtime exceptions (exceptions other than runtime exceptions are non-runtime exceptions), the Java compiler forces programmers to have capture processing, such as common Ioexeption and SqlException. For non-run-time exceptions, compilation does not pass without capturing or throwing claims processing.
In Java, the structure hierarchy of the exception class is shown in the diagram:
In Java, the parent class of all exception classes is the Throwable class, the error class is the parent of the error type exception, the exception class is the parent class of the exception type exception, and the RuntimeException class is the parent of all runtime exceptions. Classes other than RuntimeException and inheriting exception are non-runtime exceptions.
Typical runtimeexception include NullPointerException, indexoutofboundsexception, IllegalArgumentException and so on.
Typical non-runtimeexception include IOException, SqlException and so on.
Two. How exceptions are handled in Java
In Java, if you need to handle an exception, you must first capture the exception and then process the exception. How can exceptions be caught and handled by the code that might have occurred? You can use the try and catch keywords, as shown in the following code:
Try { new File ("D:/a.txt"); if (! file.exists ()) Catch (IOException e) { // Todo:handle exception}
The code that is surrounded by a try block indicates that this code may be an exception, and once an exception occurs, the exception is caught by a catch, and then the exception is handled in the catch block.
This is a way of handling exceptions. In Java also provides another kind of exception handling is thrown exception, as the name implies, that is, once an exception occurs, I throw this exception, let the caller to handle, and do not do the specific processing, the need to use the throw and throws keyword.
Let's look at an example:
Public classMain { Public Static voidMain (string[] args) {Try{createFile (); } Catch(Exception e) {//Todo:handle Exception } } Public Static voidCreateFile ()throwsioexception{File File=NewFile ("D:/a.txt"); if(!file.exists ()) file.createnewfile (); }}
The difference between this code and the previous piece of code is that the actual CreateFile method does not catch an exception, but instead throws an exception with the throws keyword declaration, which informs the caller of the method that this method might throw IOException. Then, when calling the CreateFile method in the main method, the Try...catch block is used to handle the exception capture.
Of course, you can also use the Throw keyword to manually throw an exception object. Let's look at an example:
Public classMain { Public Static voidMain (string[] args) {Try { int[] data =New int[]{1,2,3}; System.out.println (Getdatabyindex (-1, data)); } Catch(Exception e) {System.out.println (E.getmessage ()); } } Public Static intGetdatabyindex (intIndexint[] data) { if(index<0| | index>=data.length)Throw NewArrayIndexOutOfBoundsException ("array subscript out of bounds"); returnData[index]; }}
It is then captured in the catch block.
In the case of exception handling in Java, there are three ways to do exception handling for code that might occur:
1) to code block with try: Catch for exception capture processing;
2) in the code of the method body external throws to throw the declaration, tell the caller of this method this code may appear these exceptions, you need to handle carefully. There are two scenarios:
If a declaration throws an exception that is a non-runtime exception, the caller of this method must be displayed with try: Catch block or continue to throw an exception to the upper layer.
If a declaration throws an exception that is a run-time exception, the caller of this method can selectively perform exception-trapping processing.
3) throws an exception object in the code block with a throw, and there are two cases, similar to 2, in this case:
If the exception object that is thrown is a non-runtime exception, the caller of this method must be displayed with try: Catch block or continue to throw an exception to the upper layer.
If the exception object that is thrown is a run-time exception, the caller of this method can selectively perform exception capture processing.
(If the exception is eventually thrown to the main method, it is equivalent to handing the JVM automatic processing, at which point the JVM simply prints the exception information)
Three. Deep understanding of Try,catch,finally,throws,throw Five keywords
Let's take a look at the usage of the five keywords in the anomaly mechanism and the areas to be aware of.
1.try,catch,finally
The Try keyword is used to enclose logical code that may appear to be abnormal, which is not used alone and must be used with catch or finally. The Java compiler allows a combination of the following three forms:
Try...catch ...; Try....finally ...; Try....catch...finally ...
Of course the catch block can have multiple, note that the try block has only one, and the finally block is optional (but there can be at most one finally block).
Three blocks are executed in the order of try->catch->finally.
Of course, if no exception occurs, the catch block will not execute. However, the finally block is executed under any circumstances (it is very important to note that, in some cases, the action to dispose of the resource is placed in the finally block).
When there are multiple catch blocks, they are matched in the order of the catch blocks, and once the exception type is matched by a catch block, it does not match the catch block that follows.
When using try: Catch.. Finally block, be careful not to use return in the finally block, because return in finally overwrites the existing return value. Let's look at an example:
ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException; Public classMain { Public Static voidMain (string[] args) {String str=NewMain (). OpenFile (); System.out.println (str); } PublicString OpenFile () {Try{FileInputStream InputStream=NewFileInputStream ("D:/a.txt"); intCH =Inputstream.read (); System.out.println ("AAA"); return"Step1"; } Catch(FileNotFoundException e) {System.out.println ("File not Found"); return"Step2"; }Catch(IOException e) {System.out.println ("IO exception"); return"Step3"; }finally{System.out.println ("Finally block"); //return "finally"; } }}
The output of this program is:
As you can see, after filenotfoundexception occurs in a try block, it jumps to the first catch block, prints "file not found" information, assigns "Step2" to the return value, then executes the finally block, and returns the return value.
From this example, the finally block is executed regardless of whether the try block or catch block contains a return statement.
If you modify this program a little bit, the return statement comment in the finally block is removed and the result is:
The last print is "finally", and the return value is overwritten again.
So if the method has a return value, avoid using return in the Finally, which makes the program structure confusing.
2.throws and Thow Keywords
1) throws appears in the declaration of the method, indicating that the method may throw an exception, and then to the upper layer called its Method program processing, allowing throws followed by a number of exception types;
2) It is generally used when a programmer has some kind of logic to throw a particular type of exception. The throw will only appear in the method body, and when the method encounters an exception during execution, the exception information is encapsulated as an exception object and then thrown out. A very important function of the throw keyword is the conversion of the exception type (which is explained later).
Throws represents the possibility of an exception, which does not necessarily occur; throw throws an exception, and the throw throws a certain exception object. Both are negative ways of dealing with exceptions (the negativity here is not to say that this is not a good way), just throw or maybe throw exceptions, but not by methods to handle exceptions, real handling exceptions are handled by the upper call of this method.
Four. When the class inherits, how to make the exception throw declaration when the method overrides
This section discusses how to determine the type of exception-throwing declaration when a subclass overrides a parent class method. Here is the three-point principle:
1) The method of the parent class does not declare an exception, and the subclass cannot declare the exception when overriding the method;
2) If a method of the parent class declares an exception exception1, the exception declared by the subclass when overriding the method cannot be the parent class of Exception1;
3) If a method of a parent class declares an exception type that has only a non-runtime exception (run-time exception), the subclass declares an exception when overriding the method (runtime exception) and cannot contain a run-time exception (non-runtime exception).
Five. Several recommendations for exception handling and design
Here are some suggestions for exception handling as summarized by predecessors:
1. Use exceptions only where it is necessary to use exceptions, and do not use exceptions to control procedures
Using exceptions with caution, the cost of exception trapping is very high, and excessive use of the exception can severely affect the performance of the program. If you can use the IF statement and the Boolean variable in the program to make logical judgments, then minimize the use of the exception, so as to avoid unnecessary exception capture and processing. For example, the following classic program:
Public voidUseexceptionsforflowcontrol () {Try { while(true) {increasecount (); } } Catch(Maximumcountreachedexception ex) {}//Continue Execution} Public voidIncreasecount ()throwsmaximumcountreachedexception {if(Count >= 5000) Throw Newmaximumcountreachedexception (); }
The upper Useexceptionsforflowcontrol () adds count to an infinite loop until the exception is thrown, which does not make the code difficult to read, but makes the execution of the program less efficient.
2. Avoid using empty catch blocks
Doing nothing after catching an exception is the equivalent of ignoring the exception. Do not use empty catch blocks, empty catch blocks mean that you hide errors and exceptions in your program and are likely to result in an uncontrolled execution of your program. If you are very sure that the caught exception does not affect the program in any way, it is best to log the exception in log logs for easy updating and maintenance later.
3. Check the selection of exceptions and non-check exceptions
Once you decide to throw an exception, you will have to decide what exception to throw. The main problem here is whether to throw a check exception or a non-check exception.
Checking for exceptions leads to too much try...catch code, and there may be a lot of check exceptions that are not reasonably handled by developers, such as SqlException, and developers have to go try...catch, This leads to a situation where there are only a few lines of logical code, and there are many lines of code for exception capture and processing. This not only makes the logic code read obscure, but also reduces the performance of the program.
I personally recommend to avoid checking the use of exceptions, if it is true that the occurrence of the exception is very common, you need to remind the caller to handle the case, use a check exception, otherwise use a non-check exception.
Therefore, in general, I feel as far as possible to turn the inspection anomaly into a non-check exception to the upper processing.
4. Note The order of catch blocks
Do not put the exception of the upper class in the front catch block. For example, the following code:
Try{FileInputStream InputStream=NewFileInputStream ("D:/a.txt"); intCH =Inputstream.read (); System.out.println ("AAA"); return"Step1"; } Catch(IOException e) {System.out.println ("IO exception"); return"Step2"; }Catch(FileNotFoundException e) {System.out.println ("File not Found"); return"Step3"; }finally{System.out.println ("Finally block"); //return "finally";}
The filenotfoundexception of the second catch will never be captured, because FileNotFoundException is a subclass of IOException.
5. Do not put the information provided to the user in the exception information
For example, the following code:
Public classMain { Public Static voidMain (string[] args) {Try{String User=NULL; String pwd=NULL; Login (USER,PWD); } Catch(Exception e) {System.out.println (E.getmessage ()); } } Public Static voidLogin (String user,string pwd) {if(user==NULL|| pwd==NULL) Throw NewNullPointerException ("User name or password is empty"); //... }}
Show user error message best not to be confused with the program, the better way is to put all the error information in a configuration file for unified management.
6. Avoid recording the same exception in log messages multiple times
Log information is logged only where the exception first occurs. In many cases the exception is layered upward, and if it is thrown up each time, log to the log system, it will not find the root cause of the exception occurred.
7. Exception handling as far as possible at the high-level
As far as possible, the exception is thrown to the upper-level caller, which is handled when the upper-level caller is unified. If it is handled directly in each occurrence of an exception, it can cause confusion in the program exception handling process, which is detrimental to post maintenance and exception troubleshooting. Processing by the upper layer will make the process of the whole program clear and understandable.
8. Releasing Resources in finally
If you are using file reads, network operations, and database operations, remember to release resources in finally. This not only causes the program to consume less resources, but also avoids unnecessary anomalies that occur due to resources not being released.
Java Exception handling and design