[JavaSE] Super-detailed explanation of exceptions (programming ideas)

insert image description here
I hope to communicate and learn from each other through the blog. If there are any mistakes, please correct me in the comment area.


The following example:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        int num = 2/0;
    }
}

The logic of "division by 0" in this code is just a warning in the C language, but Java is a relatively safe language, and it will throw an exception directly when compiling and running.

So what is an exception?

1. What is an exception?

Exceptions refer to abnormal events that occur during program operation, usually caused by external problems (such as hardware errors, input errors). In object-oriented programming languages ​​such as Java, exceptions belong to objects.

The exception itself is an object, generating an exception is generating an exception object

Java's exception system

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-oL91wEfr-1645859727173) (C:\Users\LY\AppData\Roaming\Typora\typora-user-images\ image-20220110210046681.png)]
We all know that all classes in Java inherit from Object, and so does the Throwable class, as

we can see in the official Java documentation below

There are two inherited from the throwable class, one is Error (error), the other is Exception (abnormal), throwable is the parent class of all errors and exceptions in Java

And exceptions are divided into checked exceptions and non-checked exceptions (the exceptions that we have encountered before dividing by 0 are non-checked exceptions)

Unchecked exceptions: The Java language specification calls all exceptions derived from the Error class or RuntimeException class as unchecked exceptions (problems caused by bugs in the code of the program, null pointer exceptions, and array subscript out-of-bounds exceptions)

Checked exceptions: All other exceptions are called checked exceptions (exceptions thrown when the program is compiled) and must be handled, otherwise the code compilation cannot pass (some problems that can be solved by retrying or automatic program repair)

Error: A problem that cannot be fixed by the program at all due to the device or other hard environment

How to troubleshoot exceptions

The following code:

The running result of a "divide by 0" code written at the beginning of the article: where

java.lang.ArithmeticException is the type of exception, and by zero is the specific information of the exception

Common exception types are:

NullPointerException: Null pointer exception

ArithmeticException: Arithmetic exception

ArrayIndexOutOfBoundsException: Array index out of bounds exception

PS: There are many types of exceptions, and different exceptions have different meanings and different handling methods.

Sometimes there are many lines of exception information. These exception information are called exception information stack /exception trace stack. So how do we find the first scene of the exception in these exception information?

Click directly on the blue part of the first exception message at the top, and the cursor will automatically jump to the place where the exception was raised, so as to make corresponding modifications

2. Handling exceptions

The core idea of ​​exceptions in Java is actually to let us operate first, and then deal with problems encountered during the operation.

try...catch basic syntax

try{
    
    
	有可能出现异常的语句;
}[catch (异常类型 异常对象) {
    
    
    捕捉try当中可能出现的异常;
    可以写多个catch;
} ... ]
[finally {
    
    
	异常的出口;
    可以不写;
    finally中的代码一定会被执行,用来做一些善后工作;
}]
  • A try block contains code that may cause exceptions.
  • The catch code block is the processing behavior after an exception occurs
  • The code in the finally block is used to handle the aftermath and will be executed at the end.
  • Among them, catch and finally can be added or not added according to the situation.

Let's take the "division by 0" problem as an example

public static void main(String[] args) {
    
    
    int a = 10/0;
    System.out.println("666");
}

This program int a = 10/0;will obviously throw an exception when it arrives, and the following 666will not be printed out

If an exception occurs here, the program will be directly handed over to the JVM to handle the exception. As a result, the program will stop immediately and no longer execute downward.

So what if we want to let the program continue to execute?

Exception handling at this time

public static void main(String[] args) {
    
    
    try {
    
    
        int a = 10 / 0;
    } catch (ArithmeticException e) {
    
    
        e.printStackTrace();
    }
     System.out.println("666");
}

Put a statement that may cause an exception in try, write the type of exception you want to catch in the parentheses after catch ArithmeticException, and then you can handle the exception, e.printStackTrace(); print the exception trace stack, and finally reprint666

operation result:

When the program throws an exception, it is caught by the catch block, and the program handles the exception by itself. The result is that the program will continue to execute downward.

Note: If the type of exception to be caught in the catch is different from the type of the actual exception, it is still handed over to the JVM for processing, and the program stops immediately

What if we use Exception to catch exceptions?

The following code

public static void main(String[] args) {
    
    
    try {
    
    
        int a = 10 / 0;
    }catch (Exception e) {
    
    
        System.out.println(999);
    }catch (ArithmeticException e) {
    
    
        System.out.println(888);
    }     // 直接捕获Exception的话,后面的这些catch就没啥用了,编译器就会报错
    System.out.println("666");
}   

All exceptions inherit from Exception, so when an exception occurs, Exception can catch all exceptions, so you only need to write a catch that catches Exception, but it is not recommended to write in this way, so that you cannot get the specific exception type

finally

The code in the finally block will be executed at the end regardless of whether the catch catches the exception or not

public static void main(String[] args) {
    
    
    try {
    
    
        int a = 10 / 0;
        System.out.println("666");
    }catch (ArithmeticException e) {
    
    
        System.out.println("888");
    }finally {
    
    
        System.out.println("999");
    }
    System.out.println("777");
}

An exception occurred in the method

If there is no suitable way to handle exceptions in this method, it will be passed up the call stack

public class ExceptionLearning {
    
    
    public static void demo() {
    
    
        int a = 10/0;
    }
    public static void main(String[] args) {
    
    
        demo();
    }
}

operation result:

When executed in the demo method, an arithmetic exception is thrown, because the demo method is called by the main method, so the demo will let the main method handle the exception, but the main method does not handle the exception, and it will be handed over to the JVM for processing. program will terminate abnormally

If an exception is handled

public class ExceptionLearning {
    
    
    public static void demo() {
    
    
        int a = 10/0;
    }
    public static void main(String[] args) {
    
    
        try {
    
    
            demo();
        }catch (ArithmeticException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            System.out.println("继续向下执行");
        }
    }
}

When executed in the demo method, an arithmetic exception is thrown, because the demo method is called by the main method, so the demo will let the main method handle the exception, the main method handles the exception, and the program continues to execute downwards

Exception handling process

  1. The program executes the code in try first. If the code in try has an exception, it will end the code in try to see if it matches the exception type in catch.
  2. If a matching exception type is found, the code in the catch is executed, and if no matching exception type is found, the exception is passed up to the upper caller.
  3. Regardless of whether a matching exception type is found, the code in finally is executed (before the method ends).
  4. If the upper-level caller does not handle the exception, it will continue to pass up until the main method has no suitable code to handle the exception, and it will be handed over to the JVM for processing, at which point the program will terminate abnormally

Throwing exceptions manually

In addition to the Java compiler to throw exceptions, we can also throw exceptions for some situations ourselves

3. Custom Exception

You must know that the exception itself is an object, it must correspond to a class, then we can also customize the exception by creating a class

Source code analysis

Here we take the Arithmetic class as an example, you can first look at its source code

From the source code, you will find that the Arithmetic class inherits from the RuntimeException class, and has two constructors, one with parameters and one without parameters

customize

We can also follow Arithmetic to customize, the following code

class MyException extends RuntimeException{
    
    
    public MyException() {
    
    
        super();
    }
    public MyException(String str) {
    
    
        super(str);
    }
}
public class ExceptionLearning {
    
    
    public static void main(String[] args) throws MyException{
    
       //在方法上加上异常说明, 相当于将处理动作交给上级调用者
        int b = 0;
        if (b == 0) {
    
    
            throw new MyException("b == 0");
        }
    }
}

operation result

Notice

When we MyExceptioninherit from RuntimeException, this exception is an unchecked exception by default; when we inherit from Exception, this exception is a checked exception by default

For checked exceptions, Java mandates: If a method throws a checked exception, it must declare the exception through throws; if it throws an unchecked exception, it must declare

Guess you like

Origin blog.csdn.net/weixin_46531416/article/details/123150433