Java Essentials: Exception Handling Method!

1. Anomaly classification

Exception objects are derived from the Throwable class, and Throwable is decomposed into two branches, Error and Exception, where Error should be avoided at the code level instead of exception handling. When designing a program, generally only pay attention to the exceptions under the Exception category, which contains two exception subcategories, one is RuntimeException, the other is IOException.

1、RuntimeException

Generally speaking, RuntimeException is an exception caused by programming errors, including array out of bounds, null pointers, etc. This type of exception and exceptions under the Error category are collectively called unchecked exceptions.

2、IOException

IOException is an exception caused by non-programming errors, such as trying to read data beyond the end of the file, opening a file that does not exist, and so on. Such exceptions are called checked exceptions, and programmers need to provide exception handlers for checked exceptions.

3. Custom exception class

Sometimes you need to throw exceptions that are not included in the standard exception class, you need to define a class derived from Exception (or its subclasses) to meet the requirements.

Custom exception classes usually need to have two constructors, one without parameters and one with detailed information parameters.

// 自定义异常类
public class ExceptionSelf extends Exception{
    // 无参构造器
    public ExceptionSelf(){}
    // 带详细描述信息参数的构造器
    public ExceptionSelf(String msg){
        super(msg);
    }
}

Two, exception handling

1. Declare and throw exceptions

1) Declare the possible exceptions that this method may throw in the method header, using the throws keyword, which will throw the exceptions to the upper level for processing . If a method may have more than one exception, then you need to list all the different exceptions separated by commas. At the same time, it is not allowed to declare unchecked exceptions, that is, exceptions inherited from Error or RuntimeException.

It should be noted here that if the superclass method does not declare any checked exception, then the subclass method cannot be declared either.

2) You can also actively throw an exception object in the place where an error may occur. The throw keyword is used . If the exception is not captured here, then the exception needs to be declared in the method header.

import java.io.EOFException;
class ExceptionDemo {
    public void getName() throws EOFException{
        throw new EOFException();
    }
}

3) The difference between throw throws

Throw is to throw an exception class object, to throw in the code, the general format is throw new xx()

Throws is to throw an exception to the upper level for processing, declare in the header of the method, here is just the name of the thrown exception class, the general format is: throws xxx

2. Catch the exception

1)try...catch...finally

Put the possible exceptions in the try code block, followed by catch to handle the corresponding exceptions. A try can have multiple catch clauses (without subclass relations) to catch different exceptions. If the statement in the try is abnormal, the remaining try code will be skipped and the content of the catch statement will be executed directly. If it has a finally clause, it will be executed after the execution of the catch code. It is generally used for operations such as shutting down the IO device. Note Don't put control flow statements in it.

public static void main(String[] args){
    try{
        // 这是可能出现异常的代码块
        int sum = 0;
    }
    catch(Exception err){
        // 对对应异常进行处理
        System.out.println(err.getMessage());
    }
    finally {
        // 一般执行关闭流的操作
        System.out.println("do the close operate");
    }
}

This method is generally not applicable in tool classes, but throws exceptions to the caller for corresponding processing. A more appropriate operation is to convert the exception type in the catch clause, set the original exception as the cause of the new exception, and then throw it to the caller.

2)try-with-resource

This presents a problem. If an exception occurs in the closing operation of the finally statement, then another exception handling is required. So there is a try-with-resource method to capture exceptions, and python's with xxx as xxx operation The same is true. After the try code block runs, the resource will be automatically closed, and for this operation there can also be catch and finally clauses, which will be executed after the resource is closed.

public static void main(String[] args){
    // 把需要打开的流资源写在try后的括号中
    try(var in = new Scanner(new FileInputStream("I:/javastudy/demo.txt"), StandardCharsets.UTF_8)){
        while(in.hasNext()){
            System.out.println(in.next());
        }
    }
    // 作异常处理 此时流资源已关闭
    catch (Exception err){
        System.out.println(err.getMessage());
    }
    // 无需使用finally子句进行资源关闭
}

Three, assertion

1. Assertion is the content introduced after jdk1.4 and is represented by the keyword assert. If you need to check whether a parameter is legal in the program, you usually use the if statement to operate, but this part of the code will still be stored in the program after the test is completed. At this time, you need to introduce an assert assertion, which is not a part of the program. After the test is completed Remove the code, the program will still not be affected. (Note: The default assertion of idea is turned off, and the -ea operating parameter needs to be added to start)

2. The assertion syntax format is: assert condition: expression (can be omitted)

If the condition is not established, the program will run the expression and then terminate the operation and throw an AssertionError. If the condition is established, the program runs normally.

public static void main(String[] args){
    int sum = 6;
    assert sum==5 : "sum不等于5";
    System.out.println("---如果断言正常---");

}

3. Assertion failure is fatal and unrecoverable. Assertions should not be used to communicate with users, and should only be used for internal debugging and testing.

Four, log

1. Log framework

1) Log4j or Log4j 2 -Apache's open source project. By using Log4j, we can control the destination of log information delivery to consoles, files, GUI components, even socket servers, NT event loggers, and UNIX Syslog daemons Process, etc.; the user can also control the output format of each log; by defining the level of each log information, the user can control the log generation process in more detail. These can be configured flexibly through a configuration file (XML or Properties file) without the need to modify the program code. Log4j 2 is an upgrade of the predecessor, which refers to many features of Logback;

2) Logback -Logback is another open source diary component designed by the founder of log4j. Logback is currently divided into three modules: logback-core, logback-classic and logback-access. logback-core is the basic module of the other two modules. logback-classic is an improved version of log4j. In addition, logback-classic fully implements the SLF4J API so that you can easily change to other diary systems such as log4j or JDK14 Logging;

3) java.util.logging —— JDK built-in logging interface and implementation, the function is relatively simple;

4) Slf4j -SLF4J provides a simple and unified interface for various Logging APIs), so that users can configure their desired Logging API implementation during deployment;

5) Apache Commons Logging -The problem that Apache Commons Logging (JCL) hopes to solve is similar to that of Slf4j.

In order to avoid the cumbersomeness of introducing dependencies, the logging framework inside java is used to record various operations.

2. Log usage

1) Basic log usage: To generate a simple log, you can use the global log recorder and call the info method. Using this method, the log will be printed directly on the console.

import java.util.logging.*;
public class ExceptionSelf{
    public static void main(String[] args){
        // 关闭所有级别日志输出
        Logger.getGlobal().setLevel(Level.OFF);
        // 开启所有级别日志输出
        Logger.getGlobal().setLevel(Level.ALL);
        // 输出一条info级别的日志信息在控制台
        Logger.getGlobal().info("这是一条测试日志信息");
	}
}

2) Advanced log usage: You can customize the log recorder instead of recording all in the global recorder, and use static variables to store the reference to the log recorder to avoid garbage collection by mistake.

// 这里的日志记录器名最好定义为当前类的类名 xx.class.getName()
// 并且日志记录器一般定义之后不会再改变,所以存储它的引用的变量应为final类型
private static final Logger Log = Logger.getLogger(ExceptionSelf.class.getName());

The log levels are as follows. Generally, only logs above INFO will be recorded by default. You can also manually adjust the display level.

SEVERE
WARNING
INFO
CONFIG
FINE
FINER
FINEST
// 可以进行级别调整
Log.setLevel(Level.WARNING);

3) Precautions

a. Usually only one Logger object is used in an object. Logger should be static final, and private final is only used in a few cases where the logger needs to be passed in the constructor.

b. Output all Throwable information of Exceptions, because log output methods such as logger.error(msg) and logger.error(msg,e.getMessage()) will lose the most important StackTrace information.

c. It is not allowed to throw an exception after recording the log, because this will record the log multiple times, and only allow one log to be recorded.

d. System print (including System.out.println and System.error.println) statements are not allowed.

e. PrintStackTrace is not allowed.

f. Log performance considerations. If the code is the core code and the execution frequency is very high, it is recommended to increase the judgment in the output log, especially the low-level output <debug, info, warn>.

 

Guess you like

Origin blog.csdn.net/a159357445566/article/details/115376354