Java Basics-Exception details

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

Read Catalogue

    • First, Exception introduction
    • Second, try-catch-finally statement
    • Iii. Throw and Throws keywords
    • Four, the exception chain in Java
    • V. Concluding remarks
Java exception and exception handling back to top 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)

    

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.

  

Back to top two, try-catch-finally statements

(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:

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; 2  3 public class Trycatchtest {4     /** 5      * Divider: Divisor 6      * Result: Result 7      * Try-catch capture while loop 8      * Each loop , divider minus One, Result=result+100/divider 9      * if: Catch exception, print output "exception thrown", Return -110      * Otherwise: return result11      * @return12 *      * public     int Test1 () {from         int divider=10;15         int result=100;16         try{17 while             (divider>-1) {                 divider--;19                 result=result+100/divider;20             }21             return result;22         }catch (Exception e) {             e.printstacktrace ();             System.out.println ("Exception thrown out!! ");             return-1;26         }27}28     public     static void Main (string[] args) {         //TODO auto-generated Method Stub30         trycatchtest t1=new trycatchtest ();         System.out.println ("Test1 method execution is complete! The value of result is: "+t1.test1 ());     }33     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 capture while loop 5 * each cycle, divider minus one, Result=result+100/di Vider 6 * If: Catch exception, print output "exception thrown", return result=999 7 * Otherwise: return result 8 * Finally: printout "This is finally, haha ha!"         "Print output at the same time result 9 * @return10 */11 public int test2 () {int divider=10;13 int result=100;14 Try{15 while (divider>-1) {divider--;17 result=result+100/divider;1             8}19 return result;20}catch (Exception e) {e.printstacktrace (); 22 System.out.println ("Exception thrown out!! result=999;24}finally{25 System.out.println ("This is finally, haha ha!! System.out.println ("The value of result is:" +result);}28}30 Publi c static void Main (string[] args) {//TODO auto-generated method stub35 trycatchtest t1=new trycatchtes T ();//system.ouT.println ("Test1 Method executed! The value of result is: "+t1.test1 ()); T1.test2 (); System.out.println (" Test2 method is finished!) "); 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) {one             e.printstacktrace () ;             System.out.println ("Exception thrown out!! ")             and return result=999;14         }finally{15             System.out.println (" This is finally, haha ha!! ");             System.out.println (" The value of result is: "+result);             result;//compiler warning         }19     

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.

Back to top three, 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 Numberforma Texception (); 5     } else {6       System.out.println (s); 7     } 8     

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 will throw exception method 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) {       System.err.println ("Non-data type cannot be converted. ");       //e.printstacktrace (); 12     

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          ... 4   5       }catch (Exception1 e) {6        throw e; 7       }catch (Exception2 e) {8        System.out.println ("Error! "); 9       }10       if (a!=b) one by one        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; 2  3 public class MyException extends Exception {4      /** 5      * ERROR code 6      */7     private String ErrorCode; 8
   
    9    public     myexception () {}11     /**13      * Constructs a basic exception.      *15      * @param message16      *        Information Description      */18 public     myexception (String message) (Message         ),     }22 23 The public     , String GetErrorCode () {         errorcode;27}28, public     void Seterrorcode ( String errorCode) {         This.errorcode = errorcode;31     }32     34}
   

To throw exception information using a custom exception:

1 package com.hysum.test; 2  3 public class Main {4  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 {                             One throw new MyException ("There is no neutral person! ");                         catch (MyException e) {                             //TODO auto-generated catch block14                             e.printstacktrace ();                         }16< C13/>}else{17                          System.out.println (Sexs[i]);                      }19                 }     }21 22}

Operation Result:

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

Back to top 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;         2 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's no neutral man!")                     "); catch (MyException e) {one//TODO auto-generated catch block12                     E.printstacktrace (); runtimeexception rte=new runtimeexception (e);//Packing into RuntimeException exception 14 Rte.initcause (e); rte;//throws the new exception after the wrapper}17}else{1 8 System.out.println (sexs[i]);}20}}22 public static void Main (string[] Arg s) {//TODO auto-generated method stub24 main m =new main (); Try{27 m.test  1 ();}catch (Exception e) {e.printstacktrace (); 30           E.getcause ();//Get Raw exception 31}32 33}34 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.

Back to the top five, 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

Reference blog:

http://blog.csdn.net/p106786860/article/details/11889327

Http://www.cnblogs.com/AlanLee/p/6104492.html

http://blog.csdn.net/luoweifu/article/details/10721543

Java Basics-Exception details

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.