One article to understand what is Java exception?

1. Introduction to Java Exceptions 

You may not be unfamiliar with trycatch, and you are very proficient in using it.

When an error occurs during the running of the program, an exception will be thrown, and throwing an exception is better than terminating the program.

It is also possible to perform a trycatch operation when it is known that an error will occur, and perform some unique operations when an exception occurs.

1、Exception和Error

Both Exception and Error inherit from the Throwable class. In Java, only instances of the Throwable type can be thrown or caught. It is the basic component type of the exception handling mechanism.

Exception is a predictable abnormal situation, which can be obtained and processed outside the business.

Error is an unpredictable exception. After the error occurs, it will directly cause the JVM to be unhandled.

Exception is divided into checked exception and unchecked exception.

Checked exceptions must be caught using try catch when writing code (for example: IOException).

Unchecked exceptions, the compiler will not find out whether this place will occur once, such as null pointer exceptions, which can be avoided by specification during code writing or use. For example, the findbugs function of sts can detect the null pointer exception of the code.

2. What is the difference between NoClassDefFoundError and ClassNotFoundException?

NoClassDefFoundError is an error thrown when the JVM runtime loads a class through the classpath and cannot find the corresponding class.

ClassNotFoundException: If this exception may occur during compilation, it must be thrown during compilation.

Scenarios where NoClassDefFoundError occurs:

  1. The class or jar that the class depends on does not exist
  2. The class file exists, but in a different domain, in short, is not found

Scenarios of ClassNotFoundException:

  1. The specified class could not be found when calling the forName method of class
  2. The specified class cannot be found when the findSystemClass() method in the ClassLoader
public static void main(String[] args) {
    try {
        Class.forName("test");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Second, trycatch syntax

1. try statement

A try statement encloses a block of code in curly braces that may throw one or more exceptions.

2. catch statement

The parameters of the catch statement are similar to the declaration of the method, including an exception type and an exception object. The exception type must be a subclass of the Throwable class, which indicates the type of exception handled by the catch statement. The exception object is generated and captured by the runtime system in the code block specified by try. The curly brackets contain the processing of the object, among which Object methods can be called.

There can be multiple catch statements to handle exceptions of different classes. The Java runtime system checks the exception types handled by each catch statement from top to bottom until a catch statement with a matching type is found. Here, type matching means that the type of exception handled by the catch is exactly the same as the type of the exception object generated or its parent class. Therefore, the order of the catch statement should be from special to general.

3. finally statement

Regardless of whether an exception is thrown in the try, the code in the finally statement will be executed. The most important role of the finally statement block should be to release the requested resources.

4. throws statement

throws always appears after the function header to indicate the exceptions that the method may throw.

5. throw statement

Similar to throws, but the location is different. Throw is placed in the catch module, and the program will terminate immediately after throw is executed, and the code after throw will not be executed, except finally.

6. Throwing an exception

public void test() throws Exception{
    throw new Exception();
};

7. Catch exceptions

try{
    //代码区
}catch(Exception e){
    log.error("error: {}", e);
}finally{
    //最后必须执行的部分
}

3. The execution order of trycatch

  1. Execution starts from the first line of code in the try, and the JVM creates an exception object when it executes to the code where the exception occurs.
  2. Determine whether the catch can capture the exception object created by the jvm, ① If it is caught, jump to the catch code block, it will not end the program, and continue with the code logic in the catch; ② If it cannot be caught, print the exception information directly and end the program .
  3. If there is no exception in the try, execute the code in the try, skip the catch, and enter the finally code block.

Fourth, the principle of exception handling

  1. If an exception that needs to be detected is thrown in the method, the method must be declared, otherwise it must be caught with try-catch in the method, otherwise the compilation will fail.
  2. If the function declaring the exception is called, either try-catch or throws, otherwise the compilation fails.
  3. When to catch and when to throw? The content of the function can be solved, but if it cannot be solved with catch, use throws to tell the caller that the caller can solve it.
  4. If a function throws multiple exceptions, there must be multiple catches for targeted processing when calling.

5. Precautions for using try summarized in the work process

  1. Try not to catch Exception directly, but you should catch specific exception first, and catch Exception last. Because writing code is also a science, so that people who read the code can get more information from the code.
  2. You should not put too much code in try, just put what must be put. If you put too much code, if an exception occurs, the code behind the exception will not be executed.
  3. There can be multiple catches, and the caught exceptions should be caught by priority, with the lowest-level exception being caught first, and so on.
  4. Finally is optional in trycatch syntax, and it is not necessary, but if there is, the code in finally will be executed last regardless of whether an exception occurs. Common operations in finally are to close the stream, or delete some files that have been completed.
  5. When you trycatch a piece of code, the catch must be processed, and the return value is generally given. The boolean type and shaping generally return -1 according to the actual situation, and the String or collection type generally returns null, and then the return value is returned at the calling place. Judgment, resolutely avoid doing nothing in the catch, or returning but not receiving it.
  6. When there is a business need, you can use trycatch to make logical judgments. When reporting errors, it is a logical judgment. Sometimes it is very convenient and easy to use.

6. Disable e.printStackTrace() 

Forbid e.printStackTrace() in code.

e.printStackTrace() will only print the error information on the console (usually replaced by the log output log), and the generated error string will go to the string memory space. Once this memory space is full, there is no room for other operations. , a large number of other threads will be terminated, waiting for the release of memory space, waiting for each other, waiting for the memory to be locked, and the entire application will hang up.

7. Is the less code in trycatch the better?

There is a folk saying that the smaller the scope of trycatch, the better. Everyone knows this, why? because of low efficiency. Why is it inefficient? I no longer know.

The difference between trycatch and code without trycatch is that the former prevents Java's reordering, and the code in trycatch will not be reordered by compiler optimization. Reordering is the ability of the compiler to rearrange the execution order of statements without changing the semantics of a single-threaded program.

In short, try will prevent Java from reordering the code, which is to give up the optimization of the code by Java. Efficiency is definitely lower than sorting, so the less code in try, the better.

Of course, if you don't have a good grasp of where exceptions will explode and where they won't, try to narrow the scope of trycatch on the premise of ensuring that the code runs correctly.

The most critical part of code reordering is the real-time compiler. Let's introduce the real-time compiler, which is also the focus of this article.

Eight, just-in-time compiler

A just-in-time compiler (JIT) is a program that converts Java bytecode into execution commands that can be sent directly to the processor, and is used to improve the performance of run-time Java applications.

At runtime, the JVM loads the class files, determines the meaning of each individual bytecode, and performs the corresponding calculations. The extra use of processor and memory during interpretation means that Java applications execute slower than native applications. , that's for sure, because the code still needs to be compiled.

JIT compilers help improve the performance of Java programs by compiling bytecode to native code at runtime.

When compiling a method, the JVM directly calls the compiled native code without compiling it again. In theory, compiling each method could allow Java programs to execute at speeds close to native application speeds, provided that compilation does not require processor time and memory.

In fact, the method is not compiled the first time it is called. For each method, the JVM keeps an invocation count that is incremented each time the method is invoked, and the JVM interprets the method until its invocation count exceeds the JIT compilation threshold. Therefore, the commonly used methods will be compiled immediately after the JVM is started, and the less commonly used methods will be compiled after a longer time, or the uncommon methods will not be compiled at all. JIT compilation thresholds help the JVM to start quickly and also improve performance. Choose the threshold carefully to achieve the best balance between startup and long-term running.

After a method is compiled, the call count is reset to 0, and subsequent calls to the method continue to increment its count. When the threshold is reached, the JIT compiler will perform a second compilation with more optimization choices than the previous compilation, and the process loops back and forth until the maximum optimization level is reached. The method that is called the most frequently in the Java program, the optimization of the code is the best, and this is the reason why the extraction of common methods is advocated.

Simply put, the more frequently the code is executed, the better Java optimizes it and the faster it executes.

Nine, trycatch small demo

1. Code example

public class ExceptionTest {
    private boolean test01() {
        boolean ret = true;
        try {
            ret = test02();
        } catch (Exception e) {
            System.out.println("test01 error:" + e.getMessage());
            ret = false;
        } finally {
            System.out.println("test01,finally, return -> " + ret);
            return ret;
        }
    }
 
    private boolean test02() {
        boolean ret = true;
        try {
            //问题1:test03发生异常了,虽然trycatch了,但调用的地方没有接收
            test03();
            System.out.println("因为test03报错,我不应该执行。");
            return ret;
        } catch (Exception e) {
            System.out.println("test02 error:"+e.getMessage());
            ret = false;
            throw e;
        } finally {
            System.out.println("test02 finally, return -> " + ret);
            return ret;
        }
    }
 
    private boolean test03() throws Exception {
        boolean ret = true;
        try {
            System.out.println("我是CSDN哪吒");
            System.out.println("即将发生异常");
            int a = 1/0;
            System.out.println("发生异常后,还有走我吗?");
            return true;
        } catch (Exception e) {
            System.out.println("test03 error:"+e.getMessage());
            ret = false;
            throw e;
        } finally {
            System.out.println("test03 finally, return -> " + ret);
            return ret;
        }
    }
 
    public static void main(String[] args) {
        ExceptionTest main = new ExceptionTest();
        try {
            main.test01();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. Console output

3. Think about a problem

When you need to use trycatch in a loop, is it better to put try outside or inside?

When no exception occurs in the two, the efficiency of the two is actually the same.

10. Common Abnormalities

1. Common subclasses of Exception

2. Common subclasses of RuntimeException

3. Common subclasses of the Error class

 

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324153285&siteId=291194637