当前位置:网站首页>Summary of basic knowledge of exception handling
Summary of basic knowledge of exception handling
2022-07-03 22:05:00 【ZJH'blog】
exception handling
Exception handling classification
- 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 OutOfMemoryError Heap overflow OOM , Generally do not write targeted code for processing ( Exception handling code ), But just make changes to the original code . - Exception abnormal
General problems caused by other programming errors or accidental external factors , You can use targeted code for processing , Do not change the original code , Only add exception preprocessing :
Exception Exception Architecture
Compile time exception checked
- Runtime exception : All are RuntimeException Class and its subclass exception , Such as NullPointerException( Null pointer exception )、IndexOutOfBoundsException( Subscript out of range exception ) etc. , These exceptions are not checked , The program can choose to capture the processing , Or not . These exceptions are usually caused by program logic errors , Programs should try to avoid such exceptions from a logical point of view .
- Runtime exceptions are characterized by Java The compiler will not check it , in other words , When this kind of exception may appear in the program , Even if it doesn't work try-catch Statement capture it , It doesn't work throws The clause declares to throw it , Will also compile through .
Runtime exception unchecked
- Non runtime exception ( Compile exception ): yes RuntimeException An exception , They all belong to Exception Classes and subclasses . From the perspective of program syntax, it is an exception that must be handled , If you don't deal with , The program can't be compiled . Such as IOException、SQLException And user-defined Exception abnormal ,
- In general, no custom check exception .
exception handling
3 Exception handling statements
printStackTrance Is the most commonly used
e.toString(): Get exception types and error messages
e.getMessage(): Get the wrong message
e.printStackTrace(): Print out the exception type on the console , Error information, error location, etc
try-catch-finally
- catch There can be multiple , You can also put more than one catch Merged into a parent class catch
- finally It is not recommended to have return, But according to the situation , Here are some special return The situation of , Pay attention to the difference between basic data types and reference data types
| try in | catch in | finally in | Return value situation ( Basic data type ) | Return value situation ( Reference type ) |
|---|---|---|---|---|
| Yes | nothing | Yes | return finally Stack value in | Same as left |
| Yes | Yes and abnormal ( perform ) | Yes | perform finally, But return catch In the stack return value | perform finally And return to finally |
| nothing | Yes | Yes | If there is no abnormality finally in , If there is any abnormality, then catch in | Execute unconditionally and return finally Value |
throws Throw exceptions
This treatment method does not really solve Exception, And if you call a method ,throws Will be thrown up layer by layer , Generally, when quoting methods defined by others , The method can be throws Coming out Exception Conduct try-catch Handle , This can be more flexible
throw Active throwing
throw new RuntimeException() , Sometimes in order to ensure the integrity of logic , You need to throw exceptions to prevent operations , And back to throw The exception is handed over to the interceptor 
- throw Compile time exception (throw new Exception("")), The method is throws The corresponding compile time exception
- throw Runtime exception (throw new RuntimeException("")), The method does not need throws
for instance :throw Runtime exception , no need thorws
class Student {
int id;
public Student(int id){
if(id>0){
this.id = id;
}
else{
throw new RuntimeException("id It can't be negative ");
}
}}
Another example :throw Compile time exception , need throws
class Student {
int id;
public Student(int id) throws Exception{
if(id>0){
this.id = id;
}
else{
throw new Exception();
}
}
}

Custom exception classes
Custom exception classes need to meet
- Inherit from an exception class
- Null parameter construction and String msg structure
- Appoint serialVersionUID( Specify serialization version )
Example :
class MyException extends RuntimeException{
static final long serialVersionUID = -123456789L;
public MyException(){}
public MyException(String msg){
super(msg);
}
}
It is exactly the same as ordinary exception classes in use
边栏推荐
- Preliminary understanding of C program design
- js demo 計算本年度還剩下多少天
- Leetcode problem solving - 230 The k-th smallest element in the binary search tree
- [vulnhub shooting range] impulse: lupinone
- Global and Chinese market of wall mounted kiosks 2022-2028: Research Report on technology, participants, trends, market size and share
- Preliminary analysis of smart microwave radar module
- Minio deployment
- JS closure knowledge points essence
- Collections SQL communes
- What is the content of the securities practice examination?
猜你喜欢

Farmersworld farmers world, no faith, how to talk about success?

The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation
![Intimacy communication -- [repair relationship] - use communication to heal injuries](/img/c2/f10405e3caf570dc6bd124d65b2e93.jpg)
Intimacy communication -- [repair relationship] - use communication to heal injuries

2022 free examination questions for safety management personnel of hazardous chemical business units and reexamination examination for safety management personnel of hazardous chemical business units
![[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)](/img/29/543dce2f24130d22c1824385fbfa8f.jpg)
[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)

gslb(global server load balance)技术的一点理解

Awk getting started to proficient series - awk quick start

Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?

IPhone development swift foundation 09 assets
![[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)](/img/6c/2d48d441fee1981a271319fd9f6c23.jpg)
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
随机推荐
Getting started with DOM
The 14th five year plan and investment feasibility study report of China's industry university research cooperation Ⓧ 2022 ~ 2028
pivot ROP Emporium
Awk getting started to proficient series - awk quick start
DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power
Covariance
Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
gslb(global server load balance)技术的一点理解
Global and Chinese market of wall mounted kiosks 2022-2028: Research Report on technology, participants, trends, market size and share
No more! Technical team members resign collectively
How to install sentinel console
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
Correlation
Remember the experience of automatically jumping to spinach station when the home page was tampered with
A little understanding of GSLB (global server load balance) technology
Memory analyzer (MAT)
DR-AP40X9-A-Qualcomm-IPQ-4019-IPQ-4029-5G-4G-LTE-aluminum-body-dual-band-wifi-router-2.4GHZ-5GHz-QSD
Investment analysis and prospect trend prediction report of China's boron nitride industry Ⓨ 2022 ~ 2028
股票炒股开户注册安全靠谱吗?有没有风险的?
MySQL - idea connects to MySQL