[JavaSE] Basic Notes - Exception (Exception)

 Table of contents

1. The concept and architecture of exceptions

1.1. The concept of exception

1.2. Abnormal architecture

1.3 Classification of exceptions 

2. Exception handling

2.1. Defensive programming

2.2. Exception throwing

2.3. Exception capture

2.3.1. Exception declaration throws

2.3.2. Try-catch capture and process

3. Custom exception class


 

1. The concept and architecture of exceptions

1.1. The concept of exception

In daily development, we rack our brains to write the code perfectly. During the running of the program, some strange problems will inevitably occur. Sometimes it is difficult to control through code, such as: incorrect data format, network failure, memory alarm, etc.

When these problems occur,The JVM virtual machine automatically captures these problems and throws error messages. In Java, abnormal behavior that occurs during program execution is called an exception.

For example:

(1) Arithmetic anomaly

System.out.println(10 / 0);

(2) Array out-of-bounds exception

int[] arr = {1, 2, 3};
System.out.println(arr[100]);

(3) Null pointer exception

int[] arr = null;
System.out.println(arr.length);

As you can see from the above process,different types of exceptions in Java are described by their corresponding classes. 

1.2. Abnormal architecture

There are many types of exceptions. In order to classify and manage different exceptions or errors, Java internally maintains an exception architecture:

As you can see from the picture above:

  1. Throwable: It is the top-level class of the exception system, which derives two important subclasses, Error andException
  2. Error: Refers to serious problems that cannot be solved by the Java virtual machine, such as: Error a>, typical representatives: StackOverflowError and OutOfMemoryError, once it occurs, there is no way to recover. JVM internal errors, resource exhaustion, etc.
  3. Exception: After the exception occurs, the programmer can handle it through the code to continue the program execution. For example: cold, fever. The exception we usually call is Exception.

1.3 Classification of exceptions 

Exceptions may occur during compilation or while the program is running. Depending on the timing of occurrence, exceptions can be divided into:

1. Compile time exception

Exceptions that occur during program compilation are calledCompile-time exceptions, also called Checked Exceptions

2. Runtime exception

Exceptions that occur during program execution are calledRuntime exceptions, also called Unchecked Exceptions a>
RunTimeException and the exceptions corresponding to its subclasses are called runtime exceptions.

比如:NullPointerException、ArrayIndexOutOfBoundsException、ArithmeticException。

Note:Syntax errors that occur during compilation cannot be called exceptions. For example, System.out.println is spelled incorrectly and becomes system.out.println. At this time, an error will occur during the compilation process. This is a "compile-time" error. The runtime refers to the errors that occur during the execution of the program after the program has been compiled and obtained by the JVM.

2. Exception handling

2.1. Defensive programming

Errors exist objectively in the code. Therefore, we must notify the programmer in time when there is a problem with the program. main way

 1. LBYL: Look Before You Leap. Do sufficient inspection before operation. That is: Pre-defensive type

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

 Defect: The normal process and error handling process codes are mixed together, and the overall code is quite confusing.

2. EAFP: It's Easier to Ask Forgiveness than Permission. ". That is to say, operate first and deal with problems later. That is: Admit mistakes afterwards

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

Advantages:The normal process and error process are separated. Programmers pay more attention to the normal process, the code is clearer and easy to understand the code 

2.2. Exception throwing

When writing a program, if an error occurs in the program, the error information needs to be informed to the caller, such as parameter detection.
In Java, you can use the throw keyword to throw a specified exception object and notify the error message to caller. The specific syntax is as follows:

throw new XXXException("异常产生的原因");

【Precautions】

  1. throw must be written inside the method body
  2. The object thrown must be Exception or a subclass object of Exception
  3. If a RunTimeException or a subclass of RunTimeException is thrown, it can be handled directly by the JVM without processing.
  4. If a compile-time exception is thrown, the user must handle it, otherwise the compilation will not pass.
  5. Once an exception is thrown, the subsequent code will not be executed (unless try-catch is used to capture possible exception codes)

2.3. Exception capture

Exception capture, that is, the specific handling method of exceptions.

There are two main types:Exception declaration throws and try-catch capture processing.

2.3.1. Exception declaration throws

is after the parameter list when the method is declared. When a compile-time exception is thrown in the method and the user does not want to handle the exception, the exception can be thrown to the caller of the method through throws. That is, the current method does not handle exceptions and reminds the caller of the method to handle exceptions.

语法格式:
修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{

}

【Precautions】

  1. throws must follow the method's parameter list.
  2. The declared exception must be Exception or a subclass of Exception.
  3. If multiple exceptions are thrown inside the method, throws must be followed by multiple exception types, separated by commas. If multiple exception types are thrown and have a parent-child relationship, just declare the parent class directly.
  4. When calling a method that is declared to throw an exception,the caller must handle the exception or continue to use throws.

2.3.2. Try-catch capture and process

throws does not actually handle the exception, but reports the exception to the caller of the method that threw the exception, and the caller handles it. Ifreally wants to handle exceptions, try-catch is needed.

Syntax format:

    public static void main(String[] args) {
        try {
            // 将可能出现异常的代码放在这里
        } catch (要捕获的异常类型 e) {
            // 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类时,就会被捕获到
            // 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
        } finally {
            // 此处代码一定会被执行到
        }
        // 后序代码
        // 当异常被捕获到时,异常就被处理了,这里的后序代码一定会执行
        // 如果捕获了,由于捕获时类型不对,那就没有捕获到,这里的代码就不会被执行
    }

What is finally?

The code in finally will definitely be executed.

When writing a program,there are some specific codes that need to be executed regardless of whether an exception occurs in the program, such as the resources opened in the program: Network connections, database connections, IO streams, etc. When the program exits normally or abnormally, resources must be recycled. In addition, because exceptions will cause program jumps, some statements may not be executed , finally is used to solve this problem. 

Note: This does not mean that the code placed in try will definitely throw an exception, but that the code written in try will be caught when an exception is thrown. There is a misunderstanding that needs to be understood. 

About exception handling

There are many types of exceptions, and we have to decide according to different business scenarios.

For more serious problems (such as scenarios related to money calculation), the program should be allowed to Crash directly to prevent more serious consequences

For problems thatare not serious (most scenarios), error logs can be recorded and passedMonitoring alarmThe program notifies the programmer in time

For problems that may be recovered (network-related scenarios), you can try again.

The error log we record is the method call information where exceptions occur, which can quickly allow us to find the location where exceptions occur. In the future, we will adopt a more complete method to record exception information in actual work.

[Summary of exception handling process]

  • The program first executes the code in try.
  • If an exception occurs in the code in try, the code in try will end to see if it matches the exception type in catch.
  • If a matching exception type is found, the code in the catch is executed.
  • If no matching exception type is found, the exception will be passed up to the upper caller.
  • Regardless of whether a matching exception type is found, the code in finally will be executed (before the method ends).
  • If the upper-level caller cannot handle the exception, it will continue to be passed upward.
  • There is no appropriate code to handle the exception until the main method, and it will be handed over to the JVM for processing. At this time, the program will terminate abnormally.

3. Custom exception class

The custom exception class must inherit from Exception or RunTimeException, and implement a constructor with String type parameters. Parameter meaning: the reason for the exception.

For example, we implement auser login function.

//用于判断用户名的异常类
public class UserNameException extends RuntimeException{
    public UserNameException() {
        super();
    }

    public UserNameException(String s) {
        super(s);
    }
}
//用于判断密码的异常类
public class UserPasswordException extends RuntimeException {
    public UserPasswordException() {
        super();
    }

    public UserPasswordException(String s) {
        super(s);
    }
}

When the user logs in and the user name or password is incorrect, he or she needs to be prompted with an incorrect user name or password. However, if you use println to print directly, you can only know that the error is wrong, but you cannot know which line the error is. Defining an exception class can solve this problem, conveniently for programmers to quickly find the error reporting location in large projects.

class Login {
    public String userName = "admin";
    public String passWord = "123456";

    public void login(String userName, String passWord) {
        if(!this.userName.equals(userName)) {
            //System.out.println("用户名错误!");
            //使用自定义异常类来提示用户名错误
            throw new UserNameException("用户名错误!");
        }

        if(!this.passWord.equals(passWord)) {
            //System.out.println("密码错误!");
            //使用自定义异常类来提示密码错误
            throw new UserPasswordException("密码错误!");
        }
    }
}

public class Main {

    public static void main(String[] args) {
        try {
            Login l = new Login();
            l.login("admin", "123");
        } catch (UserNameException | UserPasswordException e) {
            e.printStackTrace();
        }

    }
}

 【operation result】

【Precautions】 

  • Custom exceptions usually inherit from Exception or RuntimeException.
  • Exceptions inherited from Exception default tochecked exceptions.
  • Exceptions inherited from RuntimeException default tounchecked exceptions.

 

 Blogger recommendation:

 [Principles of Computer Composition] Knowledge Point Consolidation - Memory Overview-CSDN Blogicon-default.png?t=N7T8https://blog.csdn.net/zzzzzhxxx/article/details/134482974?spm=1001.2014. 3001.5502

[JavaSE] Basic Notes - Library Management System (Nanny Tutorial, including source code) - CSDN Blogicon-default.png?t=N7T8https://blog.csdn.net/zzzzzhxxx/article/details/134467911 ?spm=1001.2014.3001.5502

[JavaSE] Basic Notes - Classes and Objects (Part 2) - CSDN Blogicon-default.png?t=N7T8https://blog.csdn.net/zzzzzhxxx/article/details/134248822?spm=1001.2014 .3001.5502 

If you think the author's writing is good, please give the blogger a big like and support. Your support is my biggest motivation for updating!

If you think the author's writing is good, please give the blogger a big like and support. Your support is my biggest motivation for updating!

If you think the author's writing is good, please give the blogger a big like and support. Your support is my biggest motivation for updating!

 

Guess you like

Origin blog.csdn.net/zzzzzhxxx/article/details/134564361