A detailed explanation of Java exceptions and exception handling

Source: Internet
Author: User
Tags finally block stub throw exception throwable try catch


first, Exception Introduction


What is an exception?



An exception is something that is different from the norm and is not the same as the normal Situation. In java, the case of blocking the current method or scope is called an Exception.



What is the system of exceptions in java?



All abnormal classes in 1.Java inherit from the Throwable class. Throwable mainly consists of two large categories, one is the error class, the other is the exception class;






2. Where the error class includes virtual machine errors and thread deadlock, once the error occurs, the program is completely hung, called the program terminator;






The 3.Exception class, which is often referred to as an "exception." Mainly refers to the coding, environment, user operation input problems, exception mainly include two major categories, Non-check exception (runtimeexception) and check the exception (some other EXCEPTIONS)






The 4.RuntimeException exception mainly includes the following four kinds of exceptions (there are many other exceptions, not listed here): null pointer exception, array subscript out of bounds exception, type conversion exception, arithmetic Exception. The runtimeexception exception is automatically thrown by the Java virtual machine and automatically captured (even if we do not write an exception capture statement when the runtime throws an error!! ), the large number of occurrences of such exceptions is that the code itself has a problem that should be logically resolved and the Code Improved.






5. Check the exception, the cause of the exception is various, such as the file does not exist, or the connection error and so On. Unlike its "brother" runtimeexception run exception, This exception we have to manually add a capture statement in the code to handle the exception , which is also the exception object that we learn the main processing in the Java exception Statement.





second, try-catch-finally Statement


(1) Try Block: is responsible for catching the exception, once an exception is found in the try, the control of the program will be handed over to the exception handler in the Catch Block.



  "try statement block can not exist independently and must be stored with catch or finally block"



(2) catch block: How do I handle it? For example, warn: prompt, check configuration, network connection, record error, etc. After executing the catch block, The program jumps out of the catch block and proceeds with the subsequent Code.



"considerations for writing catch blocks: The exception class that is handled by multiple catch blocks, to catch the parent class after the catch subclass is processed, because the exception will be" handled nearest "(from top to bottom). "



(3) finally: The code that is finally executed to close and release Resources.



=======================================================================



The syntax format is as Follows:



Try{
//Some exceptions that will be thrown
}catch(Exception e){
//First catch
//Code block handling the exception
}catch(Exception e){
//The second catch can have multiple catches
//Code block handling the exception
}finally{
//Final code to execute
}


When an exception occurs, the program terminates execution, is passed to the exception handler (throwing a reminder or logging, etc.), and the code outside the exception code is executed normally. Try throws many types of exceptions, and multiple catch blocks catch Multiple-clock errors .



Multiple exception handling code block order problems: the child class then the parent class (the order does not prompt the compiler to alert the error), and the finally statement block processes the code that will eventually Execute.



=======================================================================



next, We use the example to consolidate the Try-catch statement ~



First look at the Example:


1 package com.hysum.test;
Two
3 public class TryCatchTest {
4 / * *
5 * divider: divisor
6 * result: result
7 * try catch capture while loop
8 * every cycle, divide by one, result = result + 100 / divide
9 * if: catch exception, printout "exception thrown", return - 1
10 * otherwise: return result
11      * @return
12 * /
13     public int test1(){
14         int divider=10;
15         int result=100;
16         try{
17             while(divider>-1){
18                 divider--;
19                 result=result+100/divider;
20             }
21             return result;
22         }catch(Exception e){
23             e.printStackTrace();
24 system. Out. Println ("exception thrown!! "";
25             return -1;
26}
27}
28     public static void main(String[] args) {
29         // TODO Auto-generated method stub
30         TryCatchTest t1=new TryCatchTest();
31 system. Out. Println ("test1 method is finished! The value of result is: "+ T1. Test1());
32}
Thirty-three
34}


Operation Result:






Results Analysis: The exception information thrown by the red word in the result is output by E.printstacktrace (), which shows that the exception type we throw here is an arithmetic exception, followed by the reason: by zero (the arithmetic exception caused by 0), The following two lines at indicates the exact location of the code that caused the Exception.



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>



In the example above, add a test2 () method to test the execution state of the finally statement:


1 / * *
2 * divider: divisor
3 * result: result
4 * try catch catch catch while loop
5 * every cycle, divide by one, result = result + 100 / divide
6 * if an exception is caught, the printout "exception is thrown" and the result = 999 is returned
7 * otherwise: return result
8 * finally: printout "this is finally, ha ha ha!" Simultaneous printout result
9      * @return
10 * /
11     public int test2(){
12         int divider=10;
13         int result=100;
14         try{
15             while(divider>-1){
16                 divider--;
17                 result=result+100/divider;
18             }
19             return result;
20         }catch(Exception e){
21             e.printStackTrace();
22 system. Out. Println ("exception thrown!! "";
23             return result=999;
24         }finally{
25 system. Out. Println ("this is finally, ha ha ha!! "";
26 system. Out. Println ("result value is:" + result);
27}
Twenty-eight
29}
Thirty
Thirty-one
Thirty-two
33     public static void main(String[] args) {
34         // TODO Auto-generated method stub
35         TryCatchTest t1=new TryCatchTest();
36 / / system. Out. Println ("test1 method is finished! The value of result is: "+ T1. Test1());
37         t1.test2();
38 system. Out. Println ("test2 method executed! "";
39}


Operation Result:






Results Analysis: we can see from the results that the finally statement block is executed after the try block and the CATCH block statement are Executed. Finally is executed after the expression operation after return (at this point, it does not return the value of the operation, but the first to save the value to be returned, what the code in the pipe finally, the returned value will not change, is still the previous saved value), So the function return value is determined before the finally execution;



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>



Here's an interesting question: if you add a return to the finally statement block in the Test2 method above, The compiler will prompt a warning that thefinally block does not complete normally


1 public int test2(){
2         int divider=10;
3         int result=100;
4         try{
5             while(divider>-1){
6                 divider--;
7                 result=result+100/divider;
8             }
9             return result;
10         }catch(Exception e){
11             e.printStackTrace();
12 system. Out. Println ("exception thrown!! "";
13             return result=999;
14         }finally{
15 system. Out. Println ("this is finally, ha ha ha!! "";
16 system. Out. Println ("result value is:" + result);
17 return result; / / compiler warning
18}
Nineteen
20}





Parsing the problem: The return statement in the finally block may overwrite the return statement in the try block, the catch block, or, if the return statement is included in the finally block, even if the previous catch block re-throws the Exception. The statement that calls the method does not get the exception that the catch block re-throws, but instead gets the return value of the finally block and does not catch the Exception.



Solve the problem: in the face of the above situation, it is more reasonable to use neither the return statement inside the try block nor the return statement inside the finally statement, but rather the end and return of the function by using return after the finally Statements. Such as:






>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>



Summarize:



1, regardless of whether there is an exception to the wood or try and catch in the return value return,finally block code will be executed;



2, finally, It is best not to include return, or the program will exit early, the return will overwrite the return value saved in the try or Catch.



3. E.printstacktrace () can output exception Information.



4. A return value of-1 is the customary notation for throwing exceptions.



5. If there is no return statement in try,catch,finally in the method, the return result outside of the three statement blocks is Called.



6. Finally executes before returning to the keynote function after return in Try.


Iii. Throw and Throws keywords


Exception throws in Java are usually implemented using the throw and throws Keywords.



Throw----throws an exception, and it is an action that throws Exceptions.



Typically used when a program has some kind of logic, the programmer actively throws a certain type of exception. Such as:
Syntax: throw (exception object), such as:


1 public static void main(String[] args) { 
2     String s = "abc"; 
3     if(s.equals("abc")) { 
4       throw new NumberFormatException(); 
5     } else { 
6       System.out.println(s); 
7     } 
8     //function(); 
9 } 


Operation Result:


Exception in thread "main" Java.lang.NumberFormatExceptionat Test. Exceptiontest.main (exceptiontest.java:67)


Throws----declares What type of exception ( declaration ) will be thrown.



Syntax format:


1 public void method name (parameter list)
2 throws exception list{
3 / / call a method that throws an exception or:
4 throw new Exception();
5}


When a method may throw an exception, the exception used for the throws declaration may be thrown, and then passed to the upper layer to invoke its handler. Such as:


 1 public static void function() throws NumberFormatException{ 
 2     String s = "abc"; 
 3     System.out.println(Double.parseDouble(s)); 
 4   } 
 5     
 6   public static void main(String[] args) { 
 7     try { 
 8       function(); 
 9     } catch (NumberFormatException e) { 
10       System.err.println("非数据类型不能转换。"); 
11       //e.printStackTrace(); 
12     } 
13 } 


Comparison of throw and throws
1, throws appears in the method function head, and throw appears in the function body.
2. Throws indicates that there is a possibility of an exception, which does not necessarily occur; throw throws an exception, and the throw throws a certain exception object.
3, both are negative handling of the abnormal way (the negative here is not to say this way bad), just throw or may throw an exception, but not by the function to deal with the exception, the real handling of the exception by the function of the upper call Processing.



Let's look at an example:



Throws E1,e2,e3 just tells the program that this method may throw these exceptions, and the caller of the method may want to handle these exceptions, and these exceptions e1,e2,e3 may be generated by the body of the Function.
The throw is a clear place to throw this Exception. Such as:


1 void doA(int a) throws (Exception1,Exception2,Exception3){
2 try{
3          ......
Four
5       }catch(Exception1 e){
6        throw e;
7       }catch(Exception2 e){
8 system. Out. Println ("error! "";
9}
10       if(a!=b)
11 throw new exception3 (custom exception);
12}


Analysis:
1.3 Exceptions can be generated in a code block (exception1,exception2,exception3).
2. If a Exception1 exception is generated, It is then thrown after the capture and processed by the caller of the Method.
3. If a Exception2 exception is generated, the method processes itself (that is, System.out.println ("error!"). ");)。 So the method will not throw out the Exception2 exception, void DoA () throws Exception1,exception3 inside the Exception2 also do not have to Write. Because it has been captured and processed with the Try-catch Statement.
The 4.exception3 exception is an error in the logic of the method, and the programmer has handled it himself, and the caller of the method will handle the exception if it throws an exception Exception3 in the case of the logic Error. A custom exception is used here, and the exception is explained BELOW.



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>



The following points need to be noted for using the throw and throws Keywords:



The exception list for 1.throws can either throw an exception or throw multiple exceptions, separated by commas between each type of exception



2. Methods in the method body call the method that throws the exception or throws an exception first: the throw new Exception () throw is written in the method body, which means "throw exception" Action.



3. If a method invokes a method that throws an exception, you must add a try catch statement to try to catch the exception, or add a declaration that throws the exception to the Next-level caller for processing



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>



Custom exceptions



Why use custom exceptions, What are the benefits ?



1. When we work, the project is sub-module or sub-function development, basically do not you develop an entire project, the use of custom exception classes to unify the presentation of external anomalies .



2. Sometimes when we encounter certain checks or problems, we need to directly end the current request , you can throw a custom exception to the end, if you are using SPRINGMVC in the project to compare the new version of the words have controller enhancements, A controller enhancement class can be written with @controlleradvice annotations to intercept custom exceptions and respond to the appropriate information for the front end.



3. Custom exceptions can throw exceptions in certain special business logic in our project, such as "neutral". equals (sex), when gender equals neutral, we throw an exception, and Java doesn't have this Exception. Some errors in the system are java-compliant, but do not conform to the business logic of our Project.



4. Using a custom exception to inherit the associated exception to throw the treated exception information can hide the underlying exception, which is more secure, and the exception information is more Intuitive. Custom Exceptions can throw the information we want to throw, can be thrown by the information to distinguish the location of the occurrence of the exception, according to the name of the exception we can know where there is an exception, according to the exception prompt information for program Modification. For example, null pointer exception nullpointexception, we can throw the message "xxx is empty" to locate the exception location, without the output stack Information.



What's the benefit of using a custom exception, let's look at the problem with custom exceptions:



There is no doubt that we cannot expect the JVM (java virtual machine) to automatically throw a custom exception or expect the JVM to automatically handle a custom Exception. The work of discovering exceptions, throwing exceptions, and handling exceptions must be done by programmers using exception handling mechanisms in their code. This adds a number of development costs and workload accordingly, so the project is not necessary, it does not have to use the custom exception, to be able to weigh themselves.



finally, Let's take a look at how to use custom exceptions:



In Java, you can customize Exceptions. Here are some things to keep in mind when writing your own exception classes.


    • All exceptions must be subclasses of Throwable.
    • If you want to write an inspection exception class, you need to inherit the Exception class.
    • If you want to write a Run-time exception class, you need to inherit the runtimeexception class.


You can define your own exception class as Follows:



Class myexception extends Exception{ }






Let's look at an example:


1 package com.hysum.test;
Two
3 public class MyException extends Exception {
4 / * *
5 * error code
6 * /
7     private String errorCode;
Eight
Nine
10     public MyException(){}
Eleven
12 / * *
13 * construct a basic anomaly
14 *
15      * @param message
16 * information description
17 * /
18     public MyException(String message)
19 {
20         super(message);
21}
Twenty-two
Twenty-three
Twenty-four
25     public String getErrorCode() {
26         return errorCode;
27}
Twenty-eight
29     public void setErrorCode(String errorCode) {
30         this.errorCode = errorCode;
31}
Thirty-two
Thirty-three
34}


To throw exception information using a custom exception:


1 package com.hysum.test;
Two
3 public class Main {
Four
5     public static void main(String[] args) {
6         // TODO Auto-generated method stub
7 string [] sexs = {"male", "female", "neutral"};
8                   for(int i = 0; i < sexs.length; i++){
9 if ("neutral". Equals (sexs [i])){
10                           try {
11 throw new myexception ("there is no neutral person! "";
12                         } catch (MyException e) {
13                             // TODO Auto-generated catch block
14                             e.printStackTrace();
15                         }
16                      }else{
17                          System.out.println(sexs[i]);
18                      }
19                 }
20}
Twenty-one
22}


Operation Result:






It is so simple that you can throw the corresponding custom exception according to the actual business Requirements.


four, the exception chain in Java


Exceptions need to be encapsulated, but encapsulation is not enough, and you need to pass the exception .



An exception chain is an object-oriented programming technique that wraps a caught exception into a new exception and re- throws the exception handling. The original exception is saved as a property of the new exception (such as cause). The implication of this is that a method should throw exceptions that are defined at the same level of abstraction, but not discard the lower levels of Information.



I can understand the exception chain in this way:



Wrap the caught exception into a new exception, add the original exception in the new exception, and throw the new exception, which is like a chain reaction, one that causes (cause) another. The exception information that is thrown at the top of the last layer includes the lowest-level exception Information.


"scene


For example, Our JEE project is generally three layers: persistence layer, logic layer, Presentation layer, The persistence layer is responsible for interacting with the database, the logic layer is responsible for the realization of the business logic, and the presentation layer is responsible for the processing of the UI Data.



There is a module: the first time a user visits, The persistence layer needs to read the data from the user.xml, and if the file does not exist, it prompts the user to create it: if we simply discard the exception of the persistence layer, the logic layer simply does not know what happens, and it cannot provide a friendly treatment result for the presentation layer, and ultimately Mold is the presentation layer: there is no way to provide abnormal information, can only tell the user "error, I do not know what was wrong"-no friendly.



The correct approach is to encapsulate and then pass the process as Follows:



1. Package The FileNotFoundException as a Myexception.



2. Thrown to the logical layer, the logical layer determines the subsequent processing logic based on the exception code (or the custom exception Type) and then throws it to the presentation layer.



3. The presentation layer determines what to show, and if the administrator can show a low-level exception, the generic user shows the encapsulated Exception.



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>


"example
1 package com.hysum.test;
Two
3 public class Main {
4     public void test1() throws RuntimeException{
5 String [] sexs = {"male", "female", "neutral"};
6         for(int i = 0; i < sexs.length; i++){
7 if ("neutral". Equals (sexs [i])){
8                 try {
9 throw new myexception ("there is no neutral person! "";
10                 } catch (MyException e) {
11                     // TODO Auto-generated catch block
12                     e.printStackTrace();
13 runtimeException RTE = new runtimeException (E); / / package as runtimeException exception
14                     //rte.initCause(e);
15 throw RTE; / / throw a new exception after wrapping
16                 }
17            }else{
18                System.out.println(sexs[i]);
19            }
20}
21}
22     public static void main(String[] args) {
23         // TODO Auto-generated method stub
24         Main m =new Main();
Twenty-five
26         try{
27         m.test1();
28         }catch (Exception e){
29             e.printStackTrace();
30 e.getcause(); / / get the original exception
31}
Thirty-two
33}
Thirty-four
35} 


Operation Result:






Results Analysis: We can see that the console first outputs the original exception, which is output by E.getcause (), and then outputs E.printstacktrace (), where you can see caused by: the original exception and the E.getcause () output are Consistent. This is the formation of an anomaly chain. the function of Initcause () is to wrap the original exception, and call Getcause () to get the original exception when you want to know what is happening at the bottom .



>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>


"recommendations


Exceptions need to be encapsulated and passed, we do the system development, do not "devour" the exception, do not "naked" throws the exception, after encapsulation in the throw, or through the abnormal chain transmission, can achieve a more robust, friendly purpose of the System.


V. Concluding remarks


Java Exception Handling Knowledge point Miscellaneous and understanding is also a bit difficult, I am here to summarize the following points when using Java exception handling, good coding habits:



1, when dealing with abnormal operation, using logic to avoid the simultaneous auxiliary try-catch processing



2. After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed



3, for the indeterminate code, you can also add try-catch, handle the potential exception



4, try to deal with the exception, remember just simple call printstacktrace () to print



5, how to deal with the exception, according to different business needs and the type of exception to decide



6, try to add a finally statement block to release the resources occupied



A detailed explanation of Java exceptions and exception handling


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.