Java Foundation (IV.)-Exception handling mechanism and its design

Source: Internet
Author: User
Tags stack trace throwable

This article is mainly about documenting the Java exception handling mechanism (based on jdk1.7) and how to handle and design exceptions. Remember the original Java exception this piece of the time did not pay much attention to its use, thought is simple to deal with the exception, I avoid the application of such errors on the line (at first really very ignorant very naïve). It is important to know how a good exception-handling framework is when you enter the social work, such as when your project is put into use, how quickly it locates the source of the problem (what's wrong, where it went wrong, and why), which is related to the quality of your exception handling (of course, your log processing). In the case of a valid use exception, the exception type answers what is wrong with the report, and the exception stack trace answers the error, and the exception information answers why it was wrong. So if the design and processing is not good, it will take a lot of time to maintain (in this case the company will certainly be reluctant to doubt your ability).

This article will be recorded from the following aspects, if you find the wrong place also ask the big guys to point out in order to improve, thank you.

First, Java exception structure

First you need to understand what the anomaly is and why it happened. In layman's words, a program exception is a program error, and this error may be a logical error or a system error. The exception is treated as an object in Java, so we want to understand what classes in Java can be used to describe exceptions, and the hierarchy diagram below (which describes only the classes that write important ):

Ii. anomaly Classification and its common anomaly classes

In Java, all exceptions are propagated through the Throwable class and its subclasses (as can be seen from the hierarchy chart above). According to the hierarchical relationship we analyze in turn:

    • Throwable: There are two important sub-classes under it: Error and exception. All two of them are important exception handling classes, but the roles or objects they assume are different for each other, see the following analysis.
    • error: Refers to errors that the program cannot handle, also known as unchecked exceptions (Unchecked exception: The compiler does not require a forced disposition exception). For example: Java VM run error (virtual Machineerror), outofmemoryerror occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.
    • Exception: Is an exception that the program itself can handle. Any exception subclasses except runtimeexception and their subclasses are called checked exceptions (checked exceptions: Exceptions that the compiler requires to be disposed of). Natural RuntimeException and its subclasses belong to an unchecked exception.
<p>the class {@code Exception} and any subclasses that is not also * subclasses of {@link runtimeexception} is <em>checked * exceptions</em>.  Checked exceptions need to being declared in a * method or constructor ' s {@code throws} clause if they can is thrown * by the Execution of the method or constructor and propagate outside * The method or constructor boundary. * * @author  Frank Yellin * @see     java.lang.Error * @jls 11.2 compile-time Checking of Exceptions * @since   JDK1. 0 */public Class Exception extends Throwable {

According to the above Excepiton class can also be divided into these two categories: run-time exceptions and non-runtime exceptions.

    • Run-time exception: All are runtimeexception tears and their subclasses. For example, common classes: nullpointerexception (null pointer), indexoutofboundsexception (subscript out-of-bounds exception), ArithmeticException (Arithmetic exception), ClassNotFoundException (no class exception found), IllegalArgumentException (illegal parameter exception), and so on. These exceptions also belong to non-checked exceptions. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view.
    • Non-runtime exception: is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. For example, common classes: IOException, SQLException, ParseException, filenotfoundexception (Files cannot find exceptions), and so on.
    • In a comprehensive classification, throwable can be divided into this:
Third, exception handling mechanism

In Java, the exception handling mechanism is roughly: Throw an exception before catching an exception. Throwing exceptions is typically given to a Java virtual machine, but you can also manually throw exceptions (which are covered below), focusing on how to catch exceptions.

 1. Catching exceptions (try, catch, finally)

The form of the catch exception may be a combination of the above three, in the form of a try: Catch, try...finally, and try: Catch.. Finally

Main record under try: Catch.. The main points of the finally:

  1.1, where the catch block can have more than one, but pay attention to the order of catching exception classes: Subclasses must be in front of the parent class, otherwise the compilation will not pass.

    @Test public    void test1 () {        int[] arr = {1,3,5,0};        Try{for            (int i = 0; i < arr.length; i + +) {                System.out.println (10/arr[i]);}} Catch  }catch   (arithmeticexception e) {//compilation does not pass. Because the exception is caught in the preceding catch block. E.printstacktrace (); }finally{System.out.println ("end");}}        

  1.2 Pay attention to the order of execution when there is a return in the catch block: The finally statement executes before return returns.

public class Exceptiontest {        @Test public    void test1 () {        System.out.println ("Calculated result:" + sum ()); c6/>} public        int sum () {        int count = 0;        Int[] arr = {1,3,5,0}; try{for (int i = 0; i < arr.length; i ++) {count + = 10/arr[i];}} Catch (ArithmeticException e) {System.out.println ("calculation failed, denominator cannot be 0:" + e.getmessage ()); return count;} FinallySystem.out.println ("sum () End");//Will first execute } return count;}}   

Ouput:

The calculation fails, and the denominator cannot be computed for 0:/by Zerosum () End:

  1.3 When there is a return in the catch block, be aware of whether the Fianlly statement affects its return value when it modifies its return value: the base type and its string type are not changed, and the value of the member variable under the object type can be changed.

1 public classExceptiontest {2 3@Test 4 public voidTest1 () {5 System.out.println ("Base type mod1 () =" +Mol1 ()); 6 System.out.println ("String type mod2 () =" +Mol2 ()); 7 System.out.println ("Object type mod3 () =" +Mol3 ()); 8} 9 public intMol1 () {One int count = 0; int[] arr = {1,3,5,0};13 try{+ for (int i = 0; i < arr.length; i + +)) {Arr[i] = 10/Arr[i];16}17}catch(ArithmeticException e) {returnCount;19}finally{20//Basic type modification is invalid, in fact this is equivalent to a local variable, count = 1; 22}23 returnCount;24}25 PublicString Mol2 () {string msg = "Success"; int[] arr = {1,3,5,0 };29 try  {0 for (int i = +; I < arr.length; i + + ) {Arr[i] = 10/arr[i];32 }33}catch  (arithmeticexception e) {msg;36 msg = "fail" ; return }finally  {37 Invalid string modification, in fact, this is equivalent to a local variable, "fail, finally" ;}40  return  msg;41 }42 public  Stringbuff Er mol3 () {stringbuffer msg = new  stringbuffer (); int[] arr = {1,3,5,0 };45 try  {for (int i = 0; i < Arr.length; i + + ) {Arr[i] = 10/ arr[i];48 }49}catch  (arithmeticexception e) {msg.append ("fail" ); 5 1 return  msg;52}finally  {53//object type, its member variable char[] value is the one that can be changed msg.append (", finally" ); n }  msg;57 }58}            /span>                

Output

Base type Mod1 () =0 String Type mod2 () =Fail object type mod3 () =fail, finally 

  1.4 When there is a return value in a finally statement, the return statement in the catch is overwritten, and the exception that throws the catch block is invalidated. (In fact, it is not recommended)

 Public classexceptiontest {@Test Public voidtest1 () {System.out.println ("Base type mod1 () =" +Mol4 ()); System.out.println ("String type mod2 () =" +mol5 ()); }         Public intMol4 () {intCount = 0; int[] arr = {1,3,5,0}; Try{             for(inti = 0; i < arr.length; i + +) {Arr[i]= 10/Arr[i]; }        }Catch(ArithmeticException e) {returncount; }finally{Count=-1; returnCount//The direct return value does not execute in the entry catch block        }    }         Publicstring Mol5 () {string msg= "Success"; int[] arr = {1,3,5,0}; Try{             for(inti = 0; i < arr.length; i + +) {Arr[i]= 10/Arr[i]; }        }Catch(ArithmeticException e) {Throw NewArithmeticException ("Denominator cannot be 0"); }finally{            //string modification is invalid, in fact it is equivalent to a local variablemsg = "fail, finally"; returnMsg//The direct return value does not throw an exception when entering the catch block        }        //return msg;    }}

Output

Base type Mod1 () =-1 String Type mod2 ()finally

2, throw an exception, there are two ways: use throws to specify the exception, used on the method, you can use the method of throw new, in the method. Don't confuse the line.

Iv. several suggestions for designing and handling anomalies (refer to effective Java)

1, only for the exception of the situation to use the exception, do not use abnormal to control the normal flow. (I think most people would not do that, but it is also a list of things that would cause strange problems if they did)

2, avoid unnecessary use of the exception.

3, priority to use the standard exception, that is, the error message corresponding to the exception, do not throw out the exception class otherwise you will not find the source of the problem. For example, there is an array index overrun, you throw a parameter illegal exception, so that the original exception information is masked.

4. Do not ignore exceptions, that is, do not use empty catch blocks. (No exception information is available to identify the problem)

5, try to capture the details of writing. Let's say the array index is out of bounds, is it over the maximum index or less than 0?

Java Foundation (IV.)-Exception handling mechanism and its design

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.