Exception, log framework (log4j2)

1. Exception

1. Concept

An abnormal event occurs during the running of the program and the event can be handled. It will interrupt the running program.

2. Classification

Error: represents a system-level error (a serious problem)
Once a problem occurs in the system, Sun will encapsulate these errors into Error objects.
Exception: represents possible problems that may occur in the program
All exception classes are subclasses that inherit from the java.lang.Exception class
Core: Remind programmers to check local information

RuntimeException: runtime exception
Exceptions that can be avoided in programs
When an exception occurs while the program is in progress, the exception stack information will be output and the program will be terminated.
Can be captured using try-catch statement
Core: Indicates problems caused by parameter errors

CheckedException: compile-time exception
Directly inherit the Exception class
Programmers cannot foresee
The compiler will prompt
If you don't capture it, you will get a compilation error

3.Exception handling

The Java programming language uses an exception handling mechanism to provide programs with the ability to handle errors.

  • In Java, all exceptions are defined as classes
  • In addition to the built-in exception classes, Java can also customize exception classes
  • Java’s exception handling mechanism also allows you to throw exceptions yourself

4. Keyword function

5. Capture exception combinations

try{<!-- -->//try monitoring, there can only be 1
    //Statements that may cause exceptions
}catch(Exception type exception object){<!-- -->//catch can have 0~n exceptions.
    //Exception handling statement
}...
catch(Exception e){<!-- -->
    //Exception handling statement
}
}finally{<!-- -->//finally can have 0 or 1 final executions, and catch cannot be omitted at the same time.
    //Statement that will definitely be run
}

5.1try-catch block

5.1.1 no exception

All codes in try will be executed, and the code in catch will not be executed.

5.1.2 has a single exception

① Catch matched exception: The code below the exception code in the try code block will not be executed. It will jump directly to the corresponding catch and execute the statement body in the catch. If there is no corresponding catch to match it, it will still be handed over to the virtual machine for processing
②Catch mismatched exceptions: Problems in the try code block are not caught, and will eventually be handed over to the virtual machine for processing.

5.1.3 has multiple exceptions

Multiple catches will be written to match them. If multiple exceptions are caught and these exceptions have a parent-child class relationship, the parent class must be written below.

5.2 try-catch-finally block

① Regardless of whether an exception occurs, the code in the finally block will be executed.
②Java basics-the execution order of return statements in try, catch, and finally code blocks-CSDN Blog
java: test and summary of return mechanism in try catch exception
③ Unless the method to exit the virtual machine (i.e. System.exit(1);) is called in the try block or catch block, no matter what code is executed in the try block or catch block or what situation occurs, the exception handling is finally Blocks are always executed

6.Exception methods

7. Throw exception

7.1throws

  • Written at the method definition, it means declaring an exception
  • Tell the caller what exceptions may occur when using this method
public void method() throws exception class name 1, exception class name 2...{<!-- -->}

7.2throw

  • Write it inside the method and end the method
  • Manually throw the exception object and hand it to the caller. It cannot be thrown on the main() method.
  • The following code in the method is no longer executed
  • throw can only throw objects of the Throwable class or its subclasses
public void method(){<!-- -->
    throw new Exception();
}

7.3 The difference between throw and throws

  • throws is used to declare exceptions in methods, and throw is used in methods to throw exceptions.
  • Add exception class after throws and exception object after throw
  • throws means that an exception may occur, and throw means that an exception has already occurred.

8. Custom exception

When the exception types provided in the Java exception system cannot meet the needs of the program, you can customize the exception class

8.1 code illustration

/** @Desc description: Age out of range exception, age is an exception caused by parameter error*/
public class AgeOutBoundsException extends RuntimeException {<!-- -->
    /**Empty parameter construction */
    public AgeOutBoundsException() {<!-- -->
    }

    /**Construction with parameters
     * @param message*/
    public AgeOutBoundsException(String message) {<!-- -->
        super(message);
    }
}
/**Set age range 0-119*/
public void setAge(int age) throws AgeOutBoundsException{<!-- -->
    if (age<0||age>120){<!-- -->
        throw new AgeOutBoundsException(age + "Incorrect age!");
    }else {<!-- -->
        this.age = age;
    }
}
@Test
public void testAgeOutBoundsException(){<!-- -->
    Main main=new Main();
    try {<!-- -->
        main.setAge(9999);
    } catch (AgeOutBoundsException e) {<!-- -->
        e.printStackTrace();//AgeOutBoundsException: 9999 The age entered is incorrect!
    }
}

8.2 Application scenarios

  • Exceptions need to be thrown due to business logic errors in the project, but such exceptions do not exist in Java. For example, age exceptions, gender exceptions, etc.
  • Project development is generally completed by team members. In order to unify the way of displaying external exceptions, custom exceptions can be used.

2. Logging framework (log)

1. Overview

  • Mainly used to record some important operating information during system operation.
  • It is convenient to monitor the operation of the system and find the cause according to the log when a problem occurs.

2. Classification

SQL log, exception log, business log

3. Main purposes

  • Issue tracking
  • status monitoring
  • security audit

4. Operation steps

4.1 import package log4j2

4.2 Writing configuration files

The file suffix can be .xml, .json or .jsn, usually named with log4j2.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!--configuration:root node
status: can be used to specify the level of logs printed by log4j2 itself.
monitorInterval: used to set the dynamic loading time of the configuration file, the unit is seconds, the minimum is 5 seconds -->
<configuration staus="OFF">
    <!--appenders: Log output destination collection-->
    <appenders>
        <!--Console: Log output to the configuration node of the console
        name: Specify the node name
        target:SYSTEM_OUT: Output black SYSTEM_ERR: Output red -->
        <Console name="Console" target="SYSTEM_OUT">
            <!--PatternLayout: Set the output format
            %d: used to set the date and time of the output log. The default format is ISO8601
            %m: Output the message specified in the code
            %t: used to output the name of the current thread
            %5level: Output log level, -5 means left alignment and fixed output of 5 characters. If it is insufficient, add 0 to the right.
            %l: Used to output the location where the log time occurs, including the class name, the thread where it occurred, and the number of lines in the code.
            %logger: output logger name
            %msg: log text
            %n:line break-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%l] %-5level - %msg%n"/>
        </Console>
        <!--File: The configuration node where the log is output to the file
        name: Specify appenders name
        fileName: Specifies the destination file for the output log, which must be the full path file name.
        PatternLayout: Output format, if not set, the default is %m%n-->
        <File name="log" fileName="log/test.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%l] %-5level - %msg%n"/>
        </File>
    </appenders>
    <!--loggers: logger collection, multiple loggers can be configured-->
    <loggers>
        <!--root: used to specify the root log of the project. If there is no separate logger node, the log output will be configured according to this node by default.
        level: indicates the log level, from high to low OFF>fatal>error>warn>info>debug>trace>all-->
        <root level="all">
            <!--appender-ref: Specify the target appender for log output-->
            <appender-ref ref="Console"/>
            <appender-ref ref="log"/>
        </root>
    </loggers>
</configuration>

4.3 Define the logger Logger

How to get the logger

//Called in main() method
static Logger logger= LogManager.getLogger(classname.class);

4.4 Logging

The Logger class can replace System.out or System.err for developers to record log information.

4.4.1 Common methods of Logger class

4.4.2 Log Level
  • The program will output logs higher than or equal to the set level
  • The higher the log level is set, the fewer logs will be output.