当前位置:网站首页>Exception class_ Log frame
Exception class_ Log frame
2022-06-30 16:49:00 【The cool city is not warm and the night is slightly cool】
Catalog
1 Overview of exceptions
1.1 What is an anomaly ?
- An exception is an abnormal condition in the program , The program is in progress , The data causes the program to be abnormal , It eventually led to JVM The abnormal stop of
- Be careful : Statement errors are not counted in the exception system
1.2 The form of the existence of the exception
- There are types of exceptions , For example, we have been familiar with the array out of bounds exception before (ArrayIndexOutOfBoundsException), Null pointer exception (NullPointerException), Type conversion exception (ClassCastException). When an exception occurs in the program , In fact, an object of the exception is created at the location of the exception , This object carries the relevant exception information .
- Simply speaking : Exception is Java Objects of classes provided in
1.3 After an exception occurs in the program , How is it handled
- Once an exception occurs in the program , First, the downward execution will be interrupted . The transmission of exceptions depends on the handling method ( Later chapters will talk about ) And decide , If not dealt with , The default is to pass the exception to the caller of this method . Keep passing back , until JVM Received this exception , At this time, the program terminates
2 Classification of exceptions
1. Compile time exception (checked abnormal )
Exceptions that the compiler requires to be handled .
That is, the general exception caused by external factors when the program is running . Compiler requirements Java The program must catch or declare all compile time exceptions . For this kind of exception , If the program doesn't handle , It could have unexpected results .
- IOException
- FileNotFoundException
- ClassNotFoundException
2. Runtime exception (unchecked abnormal )
Exceptions that the compiler does not require mandatory handling . It generally refers to the logic error in programming , It's the exception that programmers should actively avoid .java.lang.RuntimeException Class and its subclasses are runtime exceptions . For this kind of exception , You don't have to deal with it , Because this kind of anomaly is very common , If the whole process may affect the readability and efficiency of the program .
- NullPointerException
- ArrayIndexOutOfBoundsException
- ClassCastException
- NumberFormatException
- InputMismatchException
- ArithmaticException


3 How to handle exceptions
3.1 JVM How to handle exceptions
If something goes wrong with the program , We didn't do anything , Final JVM Will do the default processing , that JVM How does it work ?
- Put the type of exception , reason , The position is printed on the console
- Program stop
Be careful : An exception occurred in the program , The object of this exception will be created in the current location , The object contains the exception information , And give the exception to the caller of this method to handle
shortcoming : Bad user experience
3.2 Manual handling of exceptions
3.2.1 Declaration exception
Declaration exception —— throws
- Modifier return type Method name ( parameter list ) throws Exception types 1 , Type of exception 2… { … }
- give an example : public void show() throws NullPointerException , ArrayIndexOutOfBoundsException { … }
effect :
- Indicates that some exceptions may occur when calling the current method , Attention should be paid to when using !
- If there are no exceptions in the current method , Then the code will execute normally
- If an exception occurs in the current method , The exception will be handed over to the caller of this method ( Wok )
package com.itheima.exception_demo; import sun.java2d.pipe.SpanShapeRenderer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /* Declaration exception —— throws Format : Modifier return type Method name ( parameter list ) throws Exception types 1 , Type of exception 2... { ... } give an example : public void show() throws NullPointerException , ArrayIndexOutOfBoundsException { .... } effect : 1 Indicates that the caller is informed that some exceptions may occur in the current method , Attention should be paid to when using ! 2 If there are no exceptions in the current method , Then the code will execute normally 3 If an exception occurs in the current method , The exception will be handed over to the caller of this method ( Wok ) demand : practice : Define two methods, a runtime exception , A declaration compile time exception ! Be careful : 1 Compile time exception, because it will be checked at compile time , So you have to write a display declaration after the method 2 Runtime exception because it only happens at runtime , So you don't have to write... After the method 3 If you declare that multiple exceptions have child parent relationships , Then just declare a parent class ( polymorphic ) */ public class Exception_Throws { public static void main(String[] args) throws ParseException{ printArr();// If an exception occurs in this method , I'll give it to you jvm To deal with StringToDate();// If an exception occurs in this method , I'll give it to you jvm To deal with } // 1 Tell the caller , Exceptions may occur in this method // 2 If there is no exception in this method , Then it will be executed normally // 3 If an exception occurs in this method , This exception will be handed over to the caller for handling // Be careful : If the declared exception is a runtime exception , Then this declaration can be omitted public static void printArr() /*throws NullPointerException*/ { int[] arr = null; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } // 1 Tell the caller , Exceptions may occur in this method // 2 If there is no exception in this method , Then it will be executed normally // 3 If an exception occurs in this method , This exception will be handed over to the caller for handling // Be careful : If the declared exception Is a compile time exception , Then it must be handled at compile time , Or the program cannot be executed public static void StringToDate() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse("2000-03-11 12:12:12"); } }
3.2.2 Throw an exception
reflection :
- There was an exception before , The virtual machine helps us create an exception object , Throw to caller . But if we need to create an exception object manually, how to write it ?
Format :
Modifier return type Method name ( parameter list ) { throw new Exception object (); }
Be careful :
The format for throwing an exception must be done inside the method
If you throw an exception manually , The following code cannot be executed
package com.itheima.exception_demo; /* Throw an exception to demonstrate : Format : Modifier return type Method name ( parameter list ) { throw new Exception object (); } Be careful : 1 The format for throwing an exception must be done inside the method 2 If you throw an exception manually , The following code cannot be executed */ public class Exception_Throw { public static void main(String[] args) { System.out.println(" There is a beautiful wife at home "); System.out.println(" And an official brother "); System.out.println(" I still have a business "); System.out.println(" Do you want to live like this ?"); // The program doesn't want to go down , How do you do it? ??? // 1 Manually create an exception // 2 The current exception is also handled by the caller of the method , That is to say jvm Handle // 3 The following code cannot be executed throw new RuntimeException(); // System.out.println(" Wu Dalang's standard life !"); } }
effect :
- In the method , When the parameters passed are incorrect , There is no point in continuing to run , Then it is thrown , Means to let the method end running .
- Tell the caller the cause of the problem in the method
package com.itheima.exception_demo;
/* The significance of throwing an exception : 1 In the method , When the parameters passed are incorrect , There is no point in continuing to run , Then it is thrown , Means to let the method end running . 2 Tell the caller that there is a problem in the method practice : Define a method , Method to receive an array , Traversing arrays in methods . demand 1 : If the array received by the method is null , Use the output statement to prompt demand 2 : If the array received by the method is null , Use throw exception to resolve reflection : What is the difference between the two methods ? */
public class Exception_Throw2 {
public static void main(String[] args) {
int[] arr = {
1, 2, 3, 4, 5};
arr = null;
// printArr1(arr);
printArr2(arr);// Receive the exception returned by the method , But this exception has jvm To deal with
}
// demand 1 : If the array received by the method is null , Use the output statement to prompt
public static void printArr1(int[] arr) {
if (arr == null) {
System.out.println(" The array is null");
} else {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
// demand 2 : If the array received by the method is null , Use throw exception to resolve
public static void printArr2(int[] arr) {
if (arr == null) {
throw new RuntimeException();
} else {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
}
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-KpTPFVkD-1656169060085)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210410224739667.png)]
3.2.3 throws and throw The difference between
- throws :
- Used after method declaration , With the exception class name
- Indicates a declared exception , Tell the caller that such an exception may occur when calling this method
- throw :
- Used in method body , Followed by the exception object name
- Indicates that an exception object is thrown manually , Inform the caller that there is an error in data transmission
3.2.4 Capture exception
Introduction to capturing and handling exceptions : try, catch
- The previous declaration or throw is to pass the exception , Let the caller know the exception information .
The capture processing is performed internally in this method , It can prevent the transmission of exceptions , So as to ensure that the program can continue to execute .
- The previous declaration or throw is to pass the exception , Let the caller know the exception information .
The format of the catch exception
try { try Store code that may cause problems in 1. Code ... 2. Code ... 3. Code ... } catch ( Exception types Variable name ) { 4. Exception handling scheme Printing exception , Get the exception cause log ......) } 5. Other code ...
Way of execution
- If try There are no problems in , How to perform ?
- From top to bottom , catch Do not execute in
- If try In the code 2 Have a problem , The question is whether the following code will be executed ?
- Not execute , It will match the current exception object with the exception type , Match successfully executed exception handling code
- If the problem is not captured , So how the program works ?
- If the exception is not caught , Virtual Opportunities help us deal with
- If try There are no problems in , How to perform ?
Multi exception capture and handling scheme
Multiple exceptions , Each exception is handled separately
try{ abnormal 1 }catch( abnormal 1){ } try{ abnormal 2 }catch( abnormal 2){ }
Multiple exceptions , A capture , Multiple processing
try{ abnormal 1 abnormal 2 }catch( abnormal 1){ }catch( abnormal 2){ }
Multiple exceptions , Exceptions are caught at one time , A processing
try{ abnormal 1 abnormal 2 }catch(Exception e){ }
3.3 Throwable Member method of
| Method name | explain |
|---|---|
| public String getMessage() | Back here throwable The detailed message string for |
| public String toString() | Returns a short description of this throw |
| public void printStackTrace() | Output the abnormal error message to the console |
3.4 Abnormal practice
package com.itheima.exception_demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/* Define a method to receive a birthday date string (xxxx year xx month xx) main Method to let the user enter a birthday date string , Call the designed method to calculate how many days you have lived on the earth . requirement : If there is an exception in parsing , Capture exception , Prompt the user to re-enter the birthday date string , Until the correct date is entered . reflection : When designing this code, think about when to catch exceptions , When to declare an exception ? */
public class ExceptionTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please input birthday (xxxx-xx-xx):");
while (true) {
String birthday = sc.nextLine();
try {
method(birthday);
break;// If birthdays are OK, end the cycle
} catch (ParseException e) {
System.out.println(" Incorrect birthday format !");
}
}
}
public static void method(String strDate) throws ParseException {
// Create date template object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Parse string
Date date = sdf.parse(strDate);
// Get birthday to 1970/1/1 Millisecond value experienced
long time1 = date.getTime();
// The current system time has expired 1970/1/1 Millisecond value experienced
Date d2 = new Date();
long time2 = d2.getTime();
System.out.println(" Live " + (time2 - time1) / (1000L * 60 * 60 * 24) + " God ");
}
}
4 Custom exception
4.1 summary
- When JDK Exception types in , When the actual business needs are not met . You can define your own exceptions . for example , Student age data , If it's a negative number or data More than the 150 Consider it illegal , You need to throw an exception .JDK There is no age anomaly in , You need to define your own exceptions
4.2 Implementation steps
- Define exception classes
- Write inheritance
- Space parameter structure
- Belt structure
4.3 Custom exception note
- If you want to customize compile time exceptions , Just inherit Exception
- If you want to customize the runtime exception , Just inherit RuntimeException
Log framework
The log in the program is used to record the information in the running process of the program , And can be permanently stored .
The information executed by the system can be selectively recorded to the specified location ( Console 、 file 、 database )
Whether to record log can be controlled in the form of switch at any time .
Architecture
Log specification : Some interfaces , The implementation framework design standards provided to the log
JCL:Commons Logging
slf4j:Simple Logging Facade for Java
Log implementation framework :Log4j、Logback、 Other implementations
Logback Log framework
- Logback By log4j Another open source logging component designed by the founder , Performance ratio log4j It is better to
- Official website :Logback Home (qos.ch)
- Logback Is based on slf4j The framework of log specification implementation
Logback It is mainly divided into three technical modules
- logback-core:logback-core Module lays the foundation for the other two modules , Equivalent to the entrance , There has to be .
- logback-classic: It is log4j An improved version of , Core function module , At the same time, it completely realizes slf4j API
- logback-access Module and Tomact and Jetty etc. Servlet Container Integration , In order to provide HTTP Access logging .
Use Logback The development steps are :
- Create a new folder under the project lib, Import Logback dependent jar Package to this folder , And add to the project library
- Must be Logback Core profile for logback.xml Copy directly to src Under the table of contents
- Get the log object in the code
- Use the log object to output log information
边栏推荐
- simpleITK读取nii遇到ITK only supports orthonormal direction cosines的错误
- 思源笔记:能否提供页面内折叠所有标题的快捷键?
- Halcon knowledge: regional topics [07]
- I 用c I 实现“栈”
- 异常类_日志框架
- Bc1.2 PD protocol
- The new tea drinks are "dead and alive", but the suppliers are "full of pots and bowls"?
- STL教程7-set、pair对组和仿函数
- [BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
- 牛客网:有多少个不同的二叉搜索树
猜你喜欢
![[download attached] installation and use of penetration test artifact Nessus](/img/ef/b6a37497010a8320cf5a49a01c2dff.png)
[download attached] installation and use of penetration test artifact Nessus

TCP Socket与TCP 连接
![Halcon knowledge: regional topics [07]](/img/18/680997127047fb24b0ee4f19d8f2c5.png)
Halcon knowledge: regional topics [07]

微信表情符号写入判决书,你发的OK、炸弹都可能成为“呈堂证供”

【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
![[machine learning] K-means clustering analysis](/img/5f/3199fbd4ff2129d3e4ea518812c9e9.png)
[machine learning] K-means clustering analysis

Hundreds of lines of code to implement a JSON parser

KDD 2022 | how far are we from the general pre training recommendation model? Universal sequence representation learning model unisrec for recommender system

华为帐号多端协同,打造美好互联生活

Mathematical modeling for war preparation 33- grey prediction model 2
随机推荐
Asp. NETCORE uses cache and AOP to prevent repeated commit
居家办公浅谈远程协助快速提效心得 | 社区征文
The inspiration from infant cognitive learning may be the key to the next generation of unsupervised machine learning
Which direction should college students choose to find jobs after graduation?
IO流_递归
RTP sending PS stream zero copy scheme
15年做糊21款硬件,谷歌到底栽在哪儿?
Li Zexiang, a legendary Chinese professor, is making unicorns in batches
JS Es5 can also create constants?
牛客网:乘积为正数的最长连续子数组
【微信小程序】小程序的宿主环境
Symantec electronic sprint technology innovation board: Tan Jian, the actual controller, is an American who plans to raise 620million yuan
聊聊远程办公那些事儿 | 社区征文
【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
microblaze 串口学习·2
2020 Blue Bridge Cup group B - move bricks - (greedy sorting +01 backpack)
Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"
[Verilog basics] summary of some concepts about clock signals (clock setup/hold, clock tree, clock skew, clock latency, clock transition..)
OpenCV中LineTypes各枚举值(LINE_4 、LINE_8 、LINE_AA )的含义
Niuke.com: minimum cost of climbing stairs