Detailed description of exceptions in Java

The so-called anomaly refers to the program runtime notification mechanism of the caller when an error occurs
, we usually put S ystem.out.println misspelled, written S ystem.out.println. In this case an error occurs during compilation, This is a " compile-time " error, not our abnormal error! !
The run-time refers to a program has been compiled by the class file, and then an error by the JVM process execution.

1. Abnormal solution:

Errors exist objectively in the code. Therefore, we have to notify the programmer in time when there is a problem in the program.
We have two main solutions :
1. LBYL : (Look Before You Leap). Do enough before the operation inspection.
2, EAFP : (. It's easier to the Ask forgiveness Within last permission) "after the acquisition is easier to forgive than it is to obtain a license."
that is the first operation, a problem reprocessing
we usually handle exceptions core idea is the second

Let's compare the difference between the above two treatments:
Let's take the glory of the king we often play as a chestnut:
1. LBYL style :

     boolean ret = false;
     
     ret = 登陆游戏();
     if (!ret) {
    
    
     //处理登陆游戏错误;
     return; 
     }
     
     ret = 开始匹配();
     if (!ret) {
    
    
     //处理匹配错误;
     return; 
     }
     
     ret = 游戏确认();
     if (!ret) {
    
    
     //处理游戏确认错误;
     return; 
     }
     
     ret = 选择英雄();
     if (!ret) {
    
    
     //处理选择英雄错误;
     return; 
     }
     
     ret = 载入游戏画面();
     if (!ret) {
    
    
     //处理载入游戏错误;
     return;
     } 

2. EAFP style:

try {
    
    
    登陆游戏();
    开始匹配();
    游戏确认();
    选择英雄();
    载入游戏画面();
   ...
} catch (登陆游戏异常) {
    
    
    处理登陆游戏异常;
} catch (开始匹配异常) {
    
    
 处理开始匹配异常;
} catch (游戏确认异常) {
    
    
 处理游戏确认异常;
} catch (选择英雄异常) {
    
    
 处理选择英雄异常;
} catch (载入游戏画面异常) {
    
    
 处理载入游戏画面异常; }

Let’s compare the above two exception handling methods, I believe that everyone can see the difference :
using the first method, the normal process and the error handling process code are mixed together, and the overall code is more confusing.;
and the second method The normal process and the error process are separated, making it easier to understand the code.

2. The basic usage of exception:

So next I will focus on the second method:
1. Give our basic format:

try{
    
     
 有可能出现异常的语句 ; 
}catch (异常类型 异常对象) {
    
    
} ... 
finally {
    
    
 异常的出口
}

2. The usage of these three:
(1) The code in the try code block is the code that may appear abnormal.
(2) The code in the catch code block is the processing behavior after the exception occurs.
(3) The code in the finally code block It is used to handle the aftermath work and will be executed at the end.
(finally has nothing to do with whether it is abnormal, it will be executed, mainly used to release resources, close files, close socket links (recommendation in finally is not recommended to write return))
(4) where catch and Finally, you can choose to add or not add according to the situation

Let's talk about the exception handling process :
1. The program first executes the code in try
2. If the code in try is abnormal, it will end the code in try to see if it matches the exception type in catch.
3. If found If the matching exception type is matched, the code in catch will be executed.
4. If no matching exception type is found, the exception will be passed up to the upper caller.
5. No matter whether a matching exception type is found, the code in finally will be executed To (execute before the end of the method).
6. If the upper caller does not handle the exception, continue to pass it upward.
7. Until the main method has no appropriate code to handle the exception, it will be handed over to the JVM for processing , The program will terminate abnormally at this time.

Note:
catch can only handle corresponding types of exceptions

int[] arr = {
    
    1, 2, 3};
try {
    
    
    System.out.println("before");
    arr = null;
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
    
    
    e.printStackTrace();
}
System.out.println("after try catch");
// 执行结果
before
Exception in thread "main" java.lang.NullPointerException
 at demo02.Test.main(Test.java:11)

At this point, the catch statement cannot catch the null pointer exception just now. Because the exception type does not match

Three, Java exception system:

So what are the exceptions? ?
Good question, let's give a picture, which is clear at a glance

Insert picture description here
Picture introduction:
1. The top-level class Throwable derives two important subclasses, Error and Exception
2. Error refers to internal errors and resource exhaustion errors during Java runtime. The application does not throw such exceptions. This kind of internal errors Once it appears, there is no power except to inform the user and terminate the program (this rarely happens).
3. Exception is the parent class of the exception class used by our programmers.
4. Exception has a subclass called RuntimeException, there is also sent birth to many of our common abnormalities class NullPointerException, IndexOutOfBoundsException so on.
5, the Java language specification will send born in class Error or RuntimeException class of all exceptions called non-checked exception , all the other exceptions referred checked exception

Four, custom exception:

Although there are a wealth of exception classes built in Java, there may be some situations in our actual scenarios that require us to extend the exception classes and create exceptions that meet our actual conditions.

Give a chestnut:
we implement a user login function

public class Test {
    
     
    private static String userName = "admin"; 
    private static String password = "123456"; 
    public static void main(String[] args) {
    
     
        try {
    
     
        login("admin", "123456"); 
        } catch (UserError userError) {
    
     
            userError.printStackTrace(); 
        } catch (PasswordError passwordError) {
    
     
            passwordError.printStackTrace(); 
        }
} 
    
    public static void login(String userName, String password) {
    
     
        if (!Test.userName.equals(userName)) {
    
     
            // TODO 处理用户名错误
            throw new UserError("用户名错误");
        } 
        if (!Test.password.equals(password)) {
    
     
            // TODO 处理密码错误
            throw new PasswordError("密码错误");
        } 
        System.out.println("登陆成功"); 
    } 
}

At this point, we may need to throw two exceptions when dealing with user name and password errors. We can extend (inherit) the existing exception class and create an exception class related to our business.

class UserError extends Exception {
    
     
    public UserError(String message) {
    
     
        super(message); 
    } 
} 

class PasswordError extends Exception {
    
     
    public PasswordError(String message) {
    
     
        super(message); 
    } 
}

Please note:
1. Custom exceptions usually inherit from Exception or RuntimeException
2. The exceptions inherited from Exception are checked exceptions by default
3. The exceptions inherited from RuntimeException are unchecked exceptions by default.

5. Interview explanation:

Insert picture description here
How to deal with exceptions:
Insert picture description here
abnormal execution flow:

Insert picture description here

It's over here. .
If the friends feel helpful, give a small compliment! !

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/109366652