Java Exception handling and design

Source: Internet
Author: User
Tags finally block getmessage throwable

Learn Java students pay Attention to!!!
The learning process encountered any problems or want to acquire learning resources, Welcome to join the Java Learning Exchange Group Number: 618528494 we learn java! together

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.

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 {  File File = new file ("d:/a.txt");  If (!file.exists ())    file.createnewfile (),} 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 class main {public    static void main (string[] Args) {        try {            createFile ()        } catch (Exception e) {
   //todo:handle exception        }    } public         static void CreateFile () throws ioexception{        File File = new Fi Le ("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 class main {public    static void main (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 int Getdatabyindex (int index,int[] data) {        if (index<0| | Index>=data.length)            throw new arrayindexoutofboundsexception ("array subscript out of bounds");        return data[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:

Import Java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.IOException;  public class main {public    static void main (string[] Args) {        String str = new Main (). openFile ();        System.out.println (str);             }         Public String openFile () {        try {            fileinputstream inputstream = new FileInputStream ("d:/a.txt");            int ch = 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 void Useexceptionsforflowcontrol () {    try {    while (true) {      increasecount ();      }    } catch ( Maximumcountreachedexception Ex) {    }    //continue execution  } public      void Increasecount () throws Maximumcountreachedexception {    if (count >=)      throw new maximumcountreachedexception ();  }

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 = new FileInputStream ("d:/a.txt");        int ch = 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 class main {public    static void main (string[] Args) {        try {            String user = null;            String pwd = null;            Login (user,pwd);        } Catch (Exception e) {            System.out.println (e.getmessage ());        }             }         public static void login (String user,string pwd) {        if (user==null| | Pwd==null)            throw new nullpointerexception ("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.

Learn Java students pay Attention to!!!
The learning process encountered any problems or want to acquire learning resources, Welcome to join the Java Learning Exchange Group Number: 618528494 we learn java! together

Java Exception handling and 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.