当前位置:网站首页>Abnormal understanding and learning
Abnormal understanding and learning
2022-07-22 17:58:00 【Daxiong who loves learning】
List of articles
Basic introduction
Java In language , The abnormal situation in program execution is called “ abnormal ”.( Note that it is not grammatical or logical errors )
Abnormal events during execution can be divided into two categories :
Error( error )
Java Serious problems that virtual machines can't solve . Such as JVM System internal error 、 Serious situations such as resource exhaustion . such as :StackOverflowError[ Stack overflow ] and OOM(out of memory),Error It's a serious mistake , The program will crash .
Exception
Other general problems caused by programming errors or accidental external factors , You can use targeted code for processing . For example, null pointer access , Trying to read a file that doesn't exist , Network connection interruption, etc ,Exception There are two main categories : Runtime exception 【 Program runtime , Abnormal occurrence 】 And compile time exceptions 【 When programming , Exception detected by compiler 】
Exception system diagram
The overview
Figure 1 :
Figure 2 :
Error error
Checkable exceptions -( Compile time exception )- (checked Exception)
Undetected abnormal -( Runtime exception )- (RuntimeException)
Summary
- error yes Java Serious problems that virtual machines can't solve
- Exceptions fall into two categories , Runtime and compile time exceptions
- Runtime exception , Compiler does not require mandatory exceptions . It generally refers to the logic error in programming , Is the exception that programmers should avoid .java.lang.RuntimeException Class and its subclasses are runtime exceptions
- For runtime exceptions , You can do nothing about it , Because this kind of anomaly is very common , If the whole process may affect the readability and efficiency of the program
- Compile time exception , Is an exception that the compiler requires to handle
Common exceptions
Five runtime exceptions
NullPointerException Null pointer exception
When an application tries to use... Where an object is needed null when , Throw the exception .
public class NullPointerException_ {
public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}
ArithmeticException The mathematical operation is abnormal
When an abnormal operation condition occurs , Throw this exception . for example , An integer “ Divide by zero ” when , Throw an instance of this class .
public class Exception01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
int res = num1 / num2
System.out.println(" Program continues ..");
}
}
ArrayIndexOutOfBoundsException Array subscript out of bounds exception
Exception thrown when accessing array with illegal index . If the index is negative or greater than or equal to the array size , The index is illegal .
public class ArrayIndexOutOfBoundsException_ {
public static void main(String[] args) {
int[] arr = {
1,2,4};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
}
}
ClassCastException Type conversion exception
When trying to cast an object to a subclass that is not an instance , Throw the exception . for example , The following code will generate a ClassCastException.
public class ClassCastException_ {
public static void main(String[] args) {
A b = new B(); // Upward transformation
B b2 = (B)b;// Move down , Here is OK
C c2 = (C)b;// Throw it here ClassCastException
}
}
class A {
}
class B extends A {
}
class C extends A {
}
NumberFormatException Incorrect number format, exception
When an application tries to convert a string to a numeric type , But the string cannot be converted to the appropriate format , Throw the exception => Using exceptions, we You can ensure that the input is a number that meets the conditions .
public class NumberFormatException_ {
public static void main(String[] args) {
String name = " education "; // take String Turn into int
int num = Integer.parseInt(name);// Throw out NumberFormatException
System.out.println(num);
}
}
Common compile time exceptions
Compilation exception means that during compilation , An exception that must be handled , Otherwise, the code cannot be compiled
Example :
- SQLException When operating the database , An exception may occur in the query table
- IOException When operating files , Abnormal occurrence
- FileNotFoundException When operating on a nonexistent file , Something goes wrong
- ClassNotFoundException Load class , When this class does not exist , abnormal
- EOFException Operation file , To the end of the file , Something goes wrong
- IllegalArguementException Parameter exception
exception handling
Exception handling is when an exception occurs , How to handle exceptions .
try-catch-finally
The programmer catches the exception in the code , Do it yourself .
try Blocks are used to contain code that can go wrong .catch Block for processing try Exception in block , You can have multiple... In the program as needed try…catch block
Basic grammar :
Shortcut key : Select the code and ctrl+alt+t
, choice try catch that will do .
try{
// You can code
// The exception object corresponding to the exception occurrence , Pass to catch block
}catch( abnormal ){
// Handling of exceptions
}
// without finally, Grammar can be passed .
Be careful :
- If something goes wrong , The code behind the exception will not execute 【 This means try Code after an exception occurs in the 】, Direct access to catch block ;
- If the exception does not occur , Then execute in sequence try Code block for , Will not enter into catch;
- If you want to, whether or not an exception occurs , All execute a piece of code ( For example, close the connection , Release resources, etc ), Use the following code -finally{ }
- There can be multiple catch sentence , Catch different exceptions ( Different business processes ), The parent class exception is required after , Subclass exception comes first , such as (Exception After ,NullPointerException before ), If something unusual happens , It only matches one catch;
- Can be done try-finally In combination with , This usage is equivalent to not catching exceptions , So the program will collapse directly / sign out . Application scenarios , Is to execute a piece of code , No matter whether there is an exception , There is a business logic that must be executed ( Written in finally in ).
throws
Throw the exception that occurs , Give it to the caller ( Method ) To deal with it , The top processor is JVM
- If there's a way ( When the statement in is executed ) May produce some kind of abnormality , But I'm not sure how to handle this exception , This method should explicitly declare that an exception is thrown , Indicates that this method will not handle these exceptions , The caller of this method is responsible for processing .
- Use... In method declarations throws Statement can declare a list of exceptions thrown ,throws The latter exception type can be the exception type generated in the method , It can also be its parent class .
Be careful :
- For compilation exceptions , The program has to deal with , Otherwise, an error is reported in the code , such as try-catch perhaps throws;
- For runtime exceptions , If there is no processing in the program , The default is throws How to deal with ;
- When a subclass overrides a parent method , Rules for throwing exceptions : Subclass override method , The type of exception thrown is either the same as the exception thrown by the parent class , Or the subtype of the type of exception thrown for the parent class ( For compilation exceptions , It doesn't matter if the operation is abnormal );
- stay throws In the process , If there is a way try-catch , It's equivalent to handling exceptions , You don't have to throws.
Custom exception
When something appears in the program “ error ”, But the error message is not in Throwable Subclass describes the handling of , You can design your own exception class at this time , Used to describe the error message .
Steps to customize exception classes
- Defining classes : Custom exception class name ( The programmer writes it himself ) Inherit Exception or RuntimeException;
- If you inherit Exception, This is a compilation exception ;
- If you inherit RuntimeException, It belongs to operation exception ( General inheritance RuntimeException, Because there is an automatic call mechanism ).
public class CustomException {
public static void main(String[] args) throws AgeException/*throws AgeException*/ {
int age = 180;
// The scope of requirements is 18 – 120 Between , Otherwise, a custom exception is thrown
if(!(age >= 18 && age <= 120)) {
// Here we can use the constructor , Set up information
throw new AgeException(" Age needs to be in 18~120 Between ");
}
System.out.println(" Your age range is correct .");
}
}
// Customize an exception
//1. In general , Our custom exception is inheritance RuntimeException
//2. That is, make the custom exception Runtime exception , Benefit time , We can use the default processing mechanism
//3. That is, it is more convenient
class AgeException extends RuntimeException {
public AgeException(String message) {
// Constructors
super(message);
}
}
throw and throws
throw It is often used to throw our custom exceptions
Example :
throw new Name of custom exception (" Abnormal information ")
边栏推荐
- 栈/堆/队列刷题(上)
- MySQL join and index
- 架构篇(一)什么是架构
- impdp content=data_ Only can you choose to skip or overwrite when there are records?
- 【HMS core】【FAQ】【Account Kit】典型问题集2
- How can VR panoramic display attract users' attention in a new way of online promotion?
- MySQL 增删改查(進階)
- 使用 Abp.Zero 搭建第三方登录模块(三):网页端开发
- 【云原生】Docker部署数据库的持久化
- 离线安装vscode
猜你喜欢
Web3 traffic aggregation platform starfish OS gives players a new paradigm experience of metauniverse
Hcip OSPF interface network type experiment report
【HMS core】【FAQ】【Account Kit】典型问题合集1
【OpenCV入门实战】利用电脑前置摄像头进行人脸检测
Niuke brush SQL
UART communication experiment (query mode)
【数据库】MySQL表的增删改查(基础)
【HMS core】【FAQ】【Account Kit】典型问题集2
2022-07-21: given a string STR and a positive number k, you can divide STR into multiple substrings at will. The purpose is to find that in a certain division scheme, there are as many palindrome subs
MySQL系列文章之四:执行计划
随机推荐
【HMS core】【FAQ】【Account Kit】典型问题合集1
How does win11 close the touch pad? Three solutions for closing the touch panel in win11
Zabbix5.0.8-ODBC监控oracle11g
vscode 安装 tools失败
【OpenCV入门实战】利用电脑前置摄像头进行人脸检测
Bigder:40/100 how to organize a use case review
【HMS core】【FAQ】【Account Kit】典型问题集2
Hcip OSPF interface network type experiment report
MySQL JDBC编程
Buu misc advanced
MySQL series article 4: execution plan
Bigder:36/100 报表测试中常见的业务名词
[how to optimize her] teach you how to locate unreasonable SQL? And optimize her~~~
Bigder:38/100 一个误操作的问题解决了
Bigder: common business terms in 36/100 report testing
Data Lake (18): Flink and iceberg integrate SQL API operations
Arrays类的理解学习
Deep learning (II) takes you to understand neural networks and activation functions
Stack / heap / queue question brushing (Part 1)
[HMS core] [push kit] set of message classification problems