Definition
Exception Handling is a new method that replaces the error code and separates the receive and process error codes.
Basic Model
Terminate model: it is assumed that the error is critical, so that the program cannot return to the exception for further execution. Once the exception is run out, it indicates that the error cannot be recovered and the execution cannot continue.
Recover model: the job of the exception handling program is to correct the error, and then try again to mobilize the method of the problem, and think that the second time can be successful.
Exception Handling principles
Negative example:
1 outputstreamwriter out =... 2 Java. SQL. connection conn =... 3 try {// retry 4 Statement stat = Conn. createstatement (); 5 resultset rs = stat.exe cutequery ("select uid, name from user"); 6 While (RS. next () {7 out. println ("ID:" + Rs. getstring ("uid") + ", name:" + Rs. getstring ("name");} // limit 8 Conn. close (); // (3) 9 out. close ();}
10 catch (exception ex) {// (2) 11 ex. printstacktrace ();} // (1), (4)
1. Do not discard exceptions easily
For example, (1) printstacktrace alone is not enough. Exceptions (almost) always mean that something is wrong, but as a programmer, these distress signals remain silent and indifferent.
There are usually four options for caught exceptions:
A. handle exceptions. Take actions against abnormal changes, such as correcting problems and giving reminders.
B. Continue to throw an exception after analysis.
C. Conversion exception. Converts a low-level exception to an application-level exception.
2. Specify the exception
If no exception is specified, the system will try to judge all possible exceptions, which will cause performance loss. In this example, the most desired exception is sqlexception, And the other exception is iooptioniton ,. Obviously, it is inappropriate to handle these two exceptions in the same Catch Block. So the best practice is catch (sqlexception) {} catch (iow.iton ){}. For other exceptions, leave them to the upper-layer call for handling.
3. Do not release occupied Resources
Exception changes the normal execution process of the program. This principle is simple but easy to ignore. If the program uses resources such as files, sockets, and JDBC connections, the occupied resources should be correctly released even if an exception occurs. Therefore, you can use finally to ensure the correct release of resources. However, be sure to avoid exceptions in finally, because finally is the last chance to execute the cleanup task.
4. Exception details
Simple pringstacktrace makes debugging programs difficult. Without specific instructions, you cannot quickly locate and determine the cause of the error even if an error is found. Therefore, when an exception occurs, you can provide some text descriptions, such as the classes, methods, and other status information that are currently being executed.
5. Too large try Blocks
It is not a good habit to put a large amount of code into a single try block. Once this is done, it means that you do not want to carefully analyze the exceptions that the Code will throw, nor do some targeted processing for these exceptions. In this way, principles 1, 2, and 4 are violated.
6. Incomplete output data
In this loop, an exception occurs in the output data. When the Catch Block is executed and the loop is interrupted, what should I do if the output data already exists? Does the user get an incomplete data copy? Or is the system generating dirty data? The ideal practice is to use the cache or transaction processing.
Finally, the optimized code is provided:
Outputstreamwriter out =... java. SQL. connection conn =... try {statement stat = Conn. createstatement (); resultset rs = stat.exe cutequery ("select uid, name from user"); While (RS. next () {out. println ("ID:" + Rs. getstring ("uid") + ", name:" + Rs. getstring ("name") ;}} catch (sqlexception sqlex) {out. println ("Warning: incomplete data ");
Throw new applicationexception ("SQL error occurred when reading data", sqlex );}
Catch (ioexception ioex ){
Throw new applicationexception ("I/O error occurred when writing data", ioex );}
Finally {
If (Conn! = NULL ){
Try {conn. Close ();}
Catch (sqlexception sqlex2 ){
System. Err (this. getclass (). getname () + ". mymethod-The database connection cannot be closed:" + sqlex2.tostring ());}}
If (OUT! = NULL ){
Try {out. Close ();}
Catch (ioexception ioex2 ){
System. Err (this. getclass (). getname () + ". mymethod-the output file cannot be closed" + ioex2.tostring ());}}}
Program Robustness-Exception Handling"