当前位置:网站首页>All the abnormal knowledge you want is here
All the abnormal knowledge you want is here
2022-06-30 12:54:00 【fiance111】
abnormal
List of articles
Understanding anomalies
First of all, you need to know what an exception is (exception)
stay Java in , Abnormal behaviors that occur during program execution are called exceptions , An exception is a type
in fact , We have been exposed to some anomalies
public static void main(String[] args) {
System.out.println(10/0);
}
This is an arithmetic anomaly , specifically , Is the division by zero exception
public static void main(String[] args) {
int[] arr = null;
System.out.println(arr.length);
}
This is a null pointer exception
Classification of exceptions
in general , There are two types of exceptions , Runtime Exceptions and compilation exceptions
The above divide by zero and null pointer exceptions are runtime exceptions , in other words , An error that is reported only at runtime is called a runtime exception
An exception that occurs during program execution , This is called a runtime exception , Also known as an unchecked exception (Unchecked Exception)
RunTimeException And the exceptions corresponding to its subclasses , Are called runtime exceptions .such as :NullPointerException、ArrayIndexOutOfBoundsException、ArithmeticException.
An exception that occurs during program compilation , This is called a compile time exception , Also known as checked exception (Checked Exception)
This is the compilation exception , It needs to be modified manually
It should be noted that , Once an exception occurs , If you don't deal with , Exception the next program will not run
public static void main(String[] args) {
int[] arr = null;
System.out.println(arr.length);
System.out.println(" Next steps ");// This line of code will not execute
}
Exception handling
We need to remind us of the problem when the program has a problem through exception handling , Better code management
Defensive abnormality
LBYL: Look Before You Leap, in other words , One step is to judge whether the operation is successful , If not, how to remedy it , This is the defensive anomaly
boolean ret = false;
ret = Log in to the game ();
if (!ret) {
Handling login game errors ;
return;
}
ret = Begin to match ();
if (!ret) {
Handling matching errors ;
return;
}
ret = Game confirmation ();
if (!ret) {
Processing game confirmation errors ;
return;
}
ret = Choose a hero ();
if (!ret) {
Handle selection hero errors ;
return;
defects : Normal flow and error handling flow code are mixed together , The overall code is chaotic . Try not to use
Admit mistakes afterwards
EAFP: It’s Easier to Ask Forgiveness than Permission That is to say, carry out normal process operation first , When the process is complete , Wrong judgment , Centralized processing of possible errors
try {
Log in to the game ();
Begin to match ();
} catch ( Login game exception ) {
Handling login game exceptions ;
} catch ( Start matching exception ) {
Processing start matching exception ;
}
The advantage of hindsight confession : Normal process and error process are separated , We pay more attention to the normal process , The code is clearer , Easy to understand code
The core idea of exception handling is to admit mistakes afterwards (EAFP)
stay Java in , Exception handling is actually the use of several keywords
throw、try、catch、finally、throws.
Throw exception
When writing a program , If an error occurs in the program , In this case, you need to inform the caller of the error information .
stay Java in , Can use throw keyword , Throw a specified exception object ( It is usually a custom exception ), Inform the caller of the error message .
If you throw a compile time exception , It must be handled (alt+enter)
Be careful :
1、throw Must be written inside the method
2、 The object thrown must be Exception perhaps Exception Subclass object of
3、 If a compile time exception is thrown , It has to be dealt with , Otherwise, it cannot be compiled
4、 Once an exception is thrown , The following code will not be executed
When the exception is a compile time exception , Be sure to handle , It is necessary to declare exceptions , Will be used throws
public static void func(int a) throws CloneNotSupportedException, FileAlreadyExistsException {
if (a == 10) {
// Generally speaking , What is thrown is a custom exception
//throw new RuntimeException(" Throw an exception ");// This is a runtime exception , There is no need for throws Statement
throw new CloneNotSupportedException(" This is a clone exception ");
}
if (a == 20) {
throw new FileAlreadyExistsException(" This is a file exception ");
}
}
public static void main(String[] args) throws CloneNotSupportedException ,FileAlreadyExistsException{
func(10);
}
Be careful :
1、throws Must follow the parameter list of the method
2、 Declared exception must be Exception perhaps Exception Subclasses of
3、 If multiple exceptions are thrown inside the method ,throws It must be followed by multiple exception types , Separated by commas .
If you throw more than one exception, the type has a parent-child relationship , Just declare the parent class directly , But try not to , It is still necessary to specify specific exceptions
public static void func(int a) throws Exception {
//Exception Is the parent of all exceptions
if (a == 10) {
// Generally speaking , What is thrown is a custom exception
//throw new RuntimeException(" Throw an exception ");
throw new CloneNotSupportedException(" This is a clone exception ");
}
if (a == 20) {
throw new FileAlreadyExistsException(" This is a file exception ");
}
}
public static void main(String[] args) throws Exception{
func(10);
}
// It is not recommended to write the parent class directly (Exception), You can write about any exception
throw And throws What's the difference ?
throw Is to throw an exception
throws Is to declare an exception
Abnormal capture
The use of throw and throws Just to avoid reporting errors , It has a big drawback , Once something unusual happens , Then the code will not execute
Generally speaking , The most common exception handling method is try-catch Capture and process
public static void main(String[] args) {
try{
int[] arr = null;
System.out.println(arr.length);
}catch(NullPointerException e){
e.printStackTrace();// Check which line is the exception
System.out.println(" Null pointer exception caught ");
// At this time, handle the exception
}catch (ArithmeticException e) {
e.printStackTrace();
System.out.println(" Caught an arithmetic exception ");
}catch (Exception e) {
// Use the parent class Exception, Only guarantee the minimum , At most, the above exceptions can be excluded , Also look further at the types of exceptions
System.out.println(" Other exceptions ");
}
System.out.println(" Other code ");
}
// Output results :
//java.lang.NullPointerException
// at Test.main(Test.java:26) The first 26 Line exception
// Null pointer exception caught
// Other code
Be careful :
1、 Even if you use try-catch,catch It should also capture the corresponding exception , If the above is a null pointer exception , result catch It catches arithmetic exceptions , It's useless , Or will it be JVM To deal with — End the program directly , The following code will not execute
2、try-catch You can catch many exceptions , But one line of code can only trigger one exception at most , So we can't meanwhile Catch multiple exceptions
3、 If there is a parent-child relationship in the exception , It must be catch Subclasses come before classes , The father is behind , Otherwise all are captured by the parent class
finally
When writing a program , Some specific code , No matter whether the program is abnormal or not , All need to be carried out , At this point, we need to use finally
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int[] arr = null;
System.out.println(arr.length);
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println(" Null pointer exception caught ");
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println(" Caught an arithmetic exception ");
} catch (Exception e) {
System.out.println(" Other exceptions ");
}finally{
scanner.close(); // Closure of resources
System.out.println(" Shut down resources ");//finally It will be carried out
}
System.out.println(" Other code ");
}
It can also be in try Add one at the end ( resources ),finally The resources will be recycled automatically
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int[] arr = null;
System.out.println(arr.length);
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println(" Null pointer exception caught ");
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println(" Caught an arithmetic exception ");
} catch (Exception e) {
System.out.println(" Other exceptions ");
} finally {
System.out.println(" Shut down resources ");// It will be carried out
}
System.out.println(" Other code ");
}
finally The statements in are bound to be executed
public static int func(int a) {
try {
if (a == 0) {
throw new ArithmeticException();// Throw an arithmetic exception
}
return 2;// Even if the a=0, The above is abnormal , This line will not be executed at all
} catch (ArithmeticException e) {
System.out.println(" Arithmetical abnormality ");
}finally {
// Not recommended in finally Inside plus return
return 30;
}
}
public static void main(String[] args) {
System.out.println(func(0));
}
// Output results :
// Arithmetical abnormality
//30
Exception handling process
There is no corresponding operation to handle exceptions , It will be by JVM Handle , Directly terminate the program
To sum up :
1、 Program first try The code in
2、 If try Exception in code in , Will be over try The code in , Look and catch Whether the exception types in match .
3、 If a matching exception type is found , Will execute catch The code in
4、 If no matching exception type is found , The exception is passed up to the upper caller .
5、 Whether or not a matching exception type is found , finally The code in will be executed to ( Execute... Before the end of the method )
6、 If the upper caller does not handle the exception , Just continue to pass up
7、 Until main Method also has no appropriate code to handle exceptions , I'll give it to JVM To process , At this point, the program will terminate the definition abnormally
Custom exception
To customize an exception, you must first specify what type of exception it is , If run-time exception, inherit RuntimeException, Compilation exceptions inherit Exception
// Customize a runtime exception
public class MyException extends RuntimeException {
// Two construction methods
public MyException() {
// Without parameters
}
public MyException(String message) {
// Contains a parameter
super(message);
}
}
import MyException.MyException;
import java.util.Scanner;
public class Test2 {
public static void function(int a) {
if (a == 0) {
throw new MyException(" This is my custom exception ");// Throw your own custom exception 1
}
}
public static void main(String[] args) {
try {
function(0);//2
} catch (MyException myException) {
myException.printStackTrace();
System.out.println(" Catch an exception ");
}
}
}
// Customize a compilation exception , Inheritance is Exception
public class MyException extends Exception {
// Runtime exception
// Two construction methods
public MyException() {
// Without parameters
}
public MyException(String message) {
// Contains a parameter
super(message);
}
}
import MyException.MyException;
import java.util.Scanner;
public class Test2 {
public static void function(int a) throws MyException {
//alt+enter Make an exception declaration
if (a == 0) {
throw new MyException(" This is my custom exception ");
}
}
public static void main(String[] args) {
try {
function(0);
} catch (MyException myException) {
myException.printStackTrace();
System.out.println(" Catch an exception ");
}
}
Realize the function of user login
You must first implement user login , First, you need to know the necessary factors for login : User name and password
secondly , Also determine whether the user name and password are correct , If not , You need to customize the exception , Error reporting
class UserNameException extends RuntimeException {
// User name exception inherited from runtime exception
public UserNameException() {
}
public UserNameException(String message) {
super(message);
}
}
class PasswordException extends RuntimeException {
public PasswordException() {
}
public PasswordException(String message) {
super(message);
}
}
public class Test3 {
private static final String userName = "admin";// To be in the following loginInfo Use in , He shall add static
private static final String password = "123456";
public static void loginInfo(String uName,String pWOrd) throws UserNameException, PasswordException {
//throws A declaration that represents an exception
if(!uName.equals(userName)){
throw new UserNameException(" User name error ");
}
if (!pWOrd.equals(password)) {
throw new PasswordException(" Wrong password ");
}
System.out.println(" The password is correct ");
}
public static void main(String[] args) {
try {
loginInfo("admin", "123456");
} catch (UserNameException e) {
e.printStackTrace();// Print out the location where the exception occurred
} catch (PasswordException e) {
e.printStackTrace();
}
}
}
Through this example of user login , I believe you will have a deeper understanding of custom exceptions .
That's all Java Knowledge points about exceptions in , If there is a mistake , Please also correct , Let's cheer together !
边栏推荐
- MATLAB小技巧(22)矩阵分析--逐步回归
- 基于ThinkPHP5封装-tronapi-波场接口-源码无加密-可二开--附接口文档-作者详细指导-2022年6月30日08:45:27
- 排查问题的方法论(适用于任何多方合作中产生的问题排查)
- Machine learning notes - Introduction to autocorrelation and partial autocorrelation
- Flinksql customizes udatf to implement topn
- Analysis of smart jiangcai login in Jiangxi University of Finance and Economics
- 独立站即web3.0,国家“十四五“规划要求企业建数字化网站!
- Shell编程概述
- Introduction to the novelty of substrate source code: comprehensive update of Boca system Boca weight calculation, optimization and adjustment of governance version 2.0
- Four ways for flinksql to customize udtf
猜你喜欢
【C】深入理解指针、回调函数(介绍模拟qsort)
Shell基础入门
ABAP工具箱 V1.0(附实现思路)
Apple executives openly "open the connection": Samsung copied the iPhone and only added a large screen
QT read / write excel--qxlsx worksheet display / hide status setting 4
Resource realization applet opening wechat official small store tutorial
Tencent cloud Database Engineer competency certification was launched, and people from all walks of life talked about talent training problems
【一天学awk】内置变量的使用
【惊了】迅雷下载速度竟然比不上虚拟机中的下载速度
Basic interview questions for Software Test Engineers (required for fresh students and test dishes) the most basic interview questions
随机推荐
【一天学awk】基础中的基础
【一天学awk】内置变量的使用
Dark horse notes - collection (common methods and traversal methods of collection)
Wechat launched the picture big bang function; Apple's self-developed 5g chip may have failed; Microsoft solves the bug that causes edge to stop responding | geek headlines
ffmpeg 杂项
Sarsa notes
[QNX Hypervisor 2.2用户手册]6.2.3 Guest与外部之间通信
Golang Basics - string and int, Int64 inter conversion
ECDSA signature verification in crypt
Unity脚本的基础语法(1)-游戏对象的常用操作
Qt读写Excel--QXlsx工作表显示/隐藏状态设置4
JMeter learning notes
Derivation of Park transformation formula for motor control
Four ways for flinksql to customize udtf
Docker installation of mysql8 and sqlyong connection error 2058 solution [jottings]
elementui中清除tinymce富文本缓存
Substrate 源码追新导读: Call调用索引化, 存储层事物化全面完成
顺应媒体融合趋势,中科闻歌携手美摄打造数智媒宣
Visual Studio配置Qt并通过NSIS实现项目打包
7 lightweight and easy-to-use tools to relieve pressure and improve efficiency for developers, and help enterprises' agile cloud launch | wonderful review of techo day