Home > Java > javaTutorial > body text

Introduction to Java exception handling methods (with code)

不言
Release: 2019-04-15 09:47:04
forward
2193 people have browsed it

This article brings you an introduction to Java exception handling methods (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Foreword: No matter in our work or life, there will always be various "errors" and various sudden "abnormalities". No matter how much preparation and testing we do, these anomalies will always appear at some point in time. If they are not handled properly or not in time, they will often lead to other new problems. Therefore, we must always pay attention to these pitfalls and need a set of "best practices" to establish a complete exception handling mechanism.

Text

Abnormal Classification

Introduction to Java exception handling methods (with code)

First of all, here I draw a structure diagram of abnormal classification.

In the JDK, Throwable is the parent class of all exceptions, which is divided into "Error" and "Exception". Error means that an uncontrollable serious error has occurred, such as OutOfMemoryError. Exceptions are subdivided into two categories. Checked exceptions (check) require us to manually try/catch or throws in the method definition. The compiler will check its legality during compilation. Unchecked exceptions (uncheck) do not require us to handle them in advance. These simple concepts must be mastered by developers. Here I will show an illustration without describing them in detail. Our "dinner" is still to come.

Reunderstand try/catch/finally

When it comes to exception handling, try/catch/finally has to be mentioned here. try cannot exist alone, it must be paired with catch, finally, or all three at the same time.
1. Try code block: Monitor the execution of the code block. If the corresponding exception is found, jump to the catch. If there is no catch, go directly to the finally block.
2. Catch code block: When the corresponding exception occurs, the code inside will be executed, either handled or thrown upward.
3. Finally code block: It must be executed regardless of whether there is an exception. It is generally used to clean up resources, release connections, etc. However, there are several situations where the code here will not be executed.

  • The code execution process does not enter the try code block.
  • The code occurs in an infinite loop, deadlock and other states in the try code block.
  • The System.exit() operation is performed in the try code block.

try/catch/finally trap

Here are two traps we may encounter when using tcf.

Code 1

public class TCFDemo {
    public static void main(String[] args) {
        //11
        System.out.println(returnVal());
    }

    static int returnVal(){
        int a = 1;
        int b = 10;
        try{
            return ++a;
        }finally {
            return ++b;
        }
    }
}
Copy after login

Trap 1: Add a return statement in finally, which will overwrite the return value of the try code. If the business logic is complex, it is easy to fall into a trap here, no Helps troubleshoot errors.

Code 2

public class TCFDemo {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
       try{
            //有可能加锁失败
            lock.lock();
            //dost
       }finally {
           lock.unlock();
       }
    }
}
Copy after login

Trap 2: Since the lock method may throw an Uncheck exception when locking, if it is in a try code block, the unlock method will inevitably be executed. At this time, since the lock is not successful, an IllegalMonitorStateException will be thrown. In this way, the latter exception overwrites the former exception information of the lock failure, so we should move the locking method outside the try code block.

Best Practice

Okay, I briefly introduced the classification of exceptions and the precautions for try/catch/finally. Now we can summarize what we are doing What are the "best practices" when handling exceptions?

  1. When you need to throw an exception upward, you need to define exceptions with business meaning according to the current business scenario. Priority is given to using exceptions defined within the industry or those defined within the team. For example, when using dubbo to make a remote service call that times out, DubboTimeoutException will be thrown instead of directly throwing RuntimeException.
  2. Do not use the return statement in the finally code block to avoid complicating the judgment of the return value.
  3. Catch the specific subclass of exception, not Exception, not throwable. This will catch all errors, including serious errors thrown by the JVM that cannot be handled.
  4. Remember not to ignore any exception (catch it without doing any processing). Even if you can ensure that it does not affect the normal operation of the logic now, no one can guarantee how the code will change in the future. Don’t dig it for yourself. pit.
  5. Don’t use exceptions as control flow. This is a very strange approach that also affects performance.
  6. Operations such as cleaning up resources and releasing connections must be placed in the finally code block to prevent memory leaks. If the logic processed by the finally block is relatively large and modular, we can encapsulate it into tool method calls, and the code will be simpler .

End

A small abnormality has a lot of knowledge, what do you think?

The above is the detailed content of Introduction to Java exception handling methods (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template