当前位置:网站首页>Detail try catch finally
Detail try catch finally
2022-07-27 12:39:00 【Rippling rippling】
abnormal
What is an anomaly ?
abnormal : That is, unusual .Java Language will program function What happens in the process Abnormal serious error This is called an exception , The handling of exceptions is called exception handling .
Abnormal consequences ?
- If something goes wrong with the program , Then the peer code will no longer run
public class Test {
public static void main(String[] args) {
System.out.println(121);
System.out.println(1/0);
System.out.println(121);
}
}

Although both are wrong , But because they are peers , So when the program reaches the first line of error code, it will return the program error , No more downward .
public class Test {
public static void main(String[] args) {
String name =null;
System.out.println(name.length());
System.out.println(1/0);
}
}
- And it will interrupt the running program , Because of this, exception handling is a very important aspect of program design , It's also a big difficulty in programming .
Classification of exceptions
Here's the picture :
exception Errors are resolved by the compiler , and error error , Compilers don't have to ask , That is JVM Things about .
Abnormal during inspection
Exception handling must be explicit , Otherwise javac The program will not be compiled
namely , you are here eclipse When writing code inside , If it's wrong , The program will show a red wavy line under the code , There is a red cross in this line , Remind you that there is a problem with this line of code .
Runtime exception
You can not explicitly handle exceptions ,javac You can still compile programs
namely : Your code itself doesn't seem to have any problems , But in fact, it doesn't conform to the rules of Mathematics .
for example
System.out.println(1/0);
Exception handling try-catch-finally
try-catch:
Wrap the wrong code , And give several options about what is wrong .
Grammatical structure :
try{
// Statement blocks that may throw exceptions
}catch(SomeException1 e){
// SomeException1 It refers to some exceptions
// When you catch SomeException1 The statement block executed when an exception of type
} catch( SomeException2 e){
// When you catch SomeException2 The statement block executed when an exception of type
}finally{
// Code that will execute regardless of whether an exception occurs
}
for example :
public class Test {
public static void main(String[] args) {
System.out.println(121);
try {
System.out.println(1/0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
System.out.println(121);
}
}

finally: No matter what try Is there any abnormality in ,finlly The code in will always execute , Generally used to release resources
for example :
public class Test {
public static void main(String[] args) {
try {
String name =null;
System.out.println(name.length());
System.out.println(1/0);
}catch (Exception e) {
System.out.println("other");
}finally {
System.out.println("z,jvhaahriFYEHDXLFG");
}
}
}
Running results :
other
z,jvhaahriFYEHDXLFG
notes :
One try There can be multiple catch,try It is not allowed to be used alone , It's like if else if else if … else
disadvantages :
If there are many mistakes , And it's an endless cycle , Then the console will always output data , Because memory is limited , But the data is still output , Then the program will remove the exception information that first enters the cache , We can't see the previous abnormal information , Complete information , To solve this problem , We introduced log4j .
example :
import org.apache.log4j.Logger;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {
int i=1;
while (true) {
try {
System.out.println(1 /0);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
i++;
}
}
}

log4j
introduce
Print the exception information to the console ——> Put into a cache , The cache has a size ——> When the cache is full , But the abnormal information is endless , The exception information that first enters the cache will be removed ——> It means that problems during the operation of the program cannot be found comprehensively ——> In order to comprehensively collect all abnormal information during system operation ,log4j The birth of ——> Output the abnormal information to a file —— Because the file is on the hard disk ——> It can be thought of as infinite
Concept :
Log4j yes Apache An open source project of , By using Log4j, You can control the format of log information and its delivery destination ( Console 、 file 、 Database etc. ), It is convenient to find problems during the operation of the system later , Thus, it is convenient to maintain the system .
How to use it? ?
To configure Log4j
step :
** First step :** Import log4j-1.2.15.jar Dependency package ;
1. Create a new project ( Here my is work), stay work So let's make a new one Folder ( It's a folder ) Name him lib. Then copy the good log4j-1.2.15.jar namely jar Paste the bag .

Choose lib Below log4j-1.2.15.jar—>BuildPath—>Add to Path

** The second step :** stay src Create a file named log4j.properties The file of , The contents of the document are as follows :
# DEBUG Set the output log level , As a result of DEBUG, therefore ERROR、WARN and INFO Level log information will also be displayed
log4j.rootLogger=DEBUG,Console,RollingFile
# Output log information to the console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{
yyyy-MM-dd HH:mm:ss}] -%l -%m%n
# Output log information to the operating system D Under the packing directory log.log In file
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=D://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{
traceId}-%m%n
Log4j Configuration file details :https://blog.csdn.net/gaohuanjie/article/details/44077551
The third step :src directories creating Test class , The code is as follows :
import org.apache.log4j.Logger;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {
try {
Class.forName("ErrorClassName");
} catch (ClassNotFoundException e) {
logger.debug(e.getMessage(),e);// Detailed daily report information
logger.info(e.getMessage(),e);// Detailed daily report information
logger.warn(e.getMessage());// Simple daily information
logger.error(e.getMessage());// Simple daily information
}
}
}
After the above three steps , Final Java The engineering structure is as follows :( Copy the teacher's ... I'm too lazy to cut )

function Test Class method , open D In the root directory log.log The corresponding log information can be seen in the file , At this time, the log information will be displayed ,Log4j The common log levels from high to low are :ERROR、WARN、INFO and DEBUG, Due to the above example Log4j Log level is DEBUG, therefore ERROR、WARN and INFO Level log information will also be displayed .
( Mine is F disc )
Generate new log files intermittently
introduce :
reflection : Now let's talk about all the exception information in a file ——> The file is very large ——> Save information in separate files
The above configuration file collects all log information into one file , So over time , The file will get bigger , The content will be more and more , This is not conducive to the later analysis of log files , To solve this problem, you can configure log4j.properties file :
# DEBUG Set the output log level , As a result of DEBUG, therefore ERROR、WARN and INFO Level log information will also be displayed
log4j.rootLogger=DEBUG,RollingFile
# Generate a log file every day (RollingFile)
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
# Full path of log file of the day
log4j.appender.RollingFile.File=d:/logs/sirius.log
# The server startup log is appended ,false: After the server starts, it will generate log files to overwrite the old
log4j.appender.RollingFile.Append=true
# Log file format
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{
traceId}-%m%n
log4j.appender.RollingFile.Threshold=DEBUG
# Set the name added after generating a file name every day , Backup name :sirius.log. Mm / DD / yyyy hrs / min .log
log4j.appender.RollingFile.DatePattern='.'yyyy-MM-dd-HH-mm'.log'
DatePattern Valid values for option are :
'.'yyyy-MM, Corresponding monthly( monthly )
'.'yyyy-ww, Corresponding weekly( Once a week )
'.'yyyy-MM-dd, Corresponding daily( Every day )
'.'yyyy-MM-dd-a, Corresponding half-daily( Every half day )
'.'yyyy-MM-dd-HH, Corresponding hourly( Every hour )
'.‘yyyy-MM-dd-HH-mm, Corresponding minutely( Every minute )
DatePattern Put the unprocessed words in single quotation marks (’) in , As above (.).
边栏推荐
- POJ1988_ Cube Stacking
- Chapter 7 exception handling
- Self built personalized automatic quotation system to cope with changeable quotation mode
- Simple blockchain day based on bolt database (2)
- Interviewer: how to deal with the data loss of redis master-slave cluster switching?
- BSP视频教程第21期:轻松一键实现串口DMA不定长收发,支持裸机和RTOS,含MDK和IAR两种玩法,比STM32CubeMX还方便(2022-07-24)
- Will causal learning open the next generation of AI? Chapter 9 Yunji datacanvas officially released the open source project of ylarn causal learning
- Top 10 international NFT exchanges
- 虚拟偶像的歌声原来是这样生成的!
- POJ1988_Cube Stacking
猜你喜欢

Go Beginner (4)

12 pictures, take you to thoroughly understand ZGC garbage collector!

Necessary foundation: Signature Verification

Dominoes staged: the beginning and end of the three arrow capital crash

How to ask questions on the road for the first time - necessary skills for self-study (with live playback)

20210519 leetcode double pointer

Implicit indicators for evaluating the advantages and disadvantages of automated testing

虚拟偶像的歌声原来是这样生成的!

The song of the virtual idol was originally generated in this way!

Solve the problem of @onetomany query falling into circular reference
随机推荐
隔离级别
Nodejs body parser middleware processes post form data of type multipart / form data, and req.body cannot receive data
Solve the problem of @onetomany query falling into circular reference
P1321 word overlay restore [getting started]
Interviewer: how to deal with the data loss of redis master-slave cluster switching?
P1876 turn on the light [getting started]
概述有名内部类与匿名内部类
CMD Chinese garbled code solution
js真伪数组转换
NFT mall /nft blind box / virtual blind box /nft transaction / customizable second opening
MySQL扩展
Chain representation and implementation of queues
C program debugging and exception handling (try catch)
SparkSubmit.main()方法提交外部参数,远程提交standalone集群任务
20210419 combined sum
Go Beginner (3)
Redis distributed online installation
[database data recovery] a data recovery case in which the disk partition where the SQL Server database is located is insufficient and an error is reported
Uniapp video video playback is not completed. It is forbidden to drag the progress bar fast forward
Basic architecture of data Lake