当前位置:网站首页>Dark horse notes - exception handling
Dark horse notes - exception handling
2022-07-07 01:20:00 【Xiaofu taps the code】
Catalog
1.1 Exception Overview 、 system
Compile time and run time exceptions
1.3 Common compile time exceptions
Compile time exception example
2.4 The default processing flow of exceptions
2.6 Compile time exception handling mechanism
There are three types of exception handling at compile time :
Exception handling 1 —— throws
Exception handling 2 —— try…catch…
Exception handling 3 —— Combination of the first two
2.6 The handling mechanism of runtime exceptions
2.7 Cases where exception handling makes code more robust
Custom exception classification
1、 Custom compile time exception
1. exception handling
1.1 Exception Overview 、 system
What is an anomaly ?
The exception is that the program is “ compile ” perhaps “ perform ” Possible problems in the process of , Be careful : Grammatical errors are not counted in the exception system .
such as : Array indexes cross the line 、 Null pointer exception 、 Date formatting exception , etc. …
Why learn to be abnormal ?
Once an exception occurs , If not handled in advance , The program will exit JVM The virtual machine terminates .
Study anomalies and avoid them , Then handle the exception in advance , It reflects the safety of the program , Robustness, .
Abnormal system
Error: System level issues 、JVM Quit and so on , Code can't control .
Exception:java.lang It's a bag , Called exception class , It represents the problem that the program itself can handle
RuntimeException And its subclasses : Runtime exception , No errors are reported during compilation . ( Null pointer exception , Array index out of bounds exception )
except RuntimeException All exceptions except : Compile time exception , What must be handled at compile time , Otherwise, the program cannot be compiled . ( Date formatting exception ).
Compile time and run time exceptions
Compile time exception , Is compiling into class Exceptions that must be handled when file , It is also called the tested exception
Runtime exception , Compiling into class Documents do not need to be processed , Possible exceptions when running bytecode files .
Simply speaking :
Compile time exceptions are exceptions that occur during compilation , Runtime exceptions are exceptions that occur at runtime .
summary :
1. What's the exception ?
Exceptions are errors that may occur during the compilation or execution of code .
2. Exceptions fall into several categories ?
Compile time exception 、 Runtime exception .
Compile time exception : No inheritance RuntimeExcpetion It's abnormal , There will be errors in the compilation phase .
Runtime exception : Inherited from RuntimeException Exception or subclass of , No error during compilation , The operation may report an error .
3. The purpose of learning abnormality ?
Avoid anomalies , Handle possible exceptions at the same time , Make the code more robust .
1.2 Common runtime exceptions
Runtime exception
Inherit directly from RuntimeException Or a subclass of that , No errors are reported during compilation , Possible errors at runtime .
Examples of runtime exceptions
Array index out of bounds exception : ArrayIndexOutOfBoundsException
Null pointer exception : NullPointerException, There is no problem with direct output , However, the function of calling a variable with a null pointer will report an error .
Abnormal mathematical operation :ArithmeticException
Type conversion exception :ClassCastException
The digital conversion is abnormal : NumberFormatException
Runtime exception : Generally, the programmer's business is not considered well or the programming logic is not rigorous , There is something wrong with your level !
/**
expand : Common runtime exceptions .( Interview questions )
The concept of runtime exceptions :
Inherited from RuntimeException Or its subclasses ,
There will be no errors in the compilation phase , It is a possible error in the run-time phase ,
Runtime exceptions can be handled or not handled in the compilation phase , Code compilation can pass !!
1. Array index out of bounds exception : ArrayIndexOutOfBoundsException.
2. Null pointer exception : NullPointerException.
There is no problem with direct output . However, the function of calling a variable with a null pointer will report an error !!
3. Type conversion exception :ClassCastException.
4. Iterator traversal does not have this element exception :NoSuchElementException.
5. Abnormal mathematical operation :ArithmeticException.
6. The digital conversion is abnormal : NumberFormatException.
Summary :
Runtime exceptions inherit RuntimeException , No error during compilation , Only when running can errors occur !
*/
public class ExceptionDemo {
public static void main(String[] args) {
System.out.println(" Program starts ......");
/** 1. Array index out of bounds exception : ArrayIndexOutOfBoundsException.*/
int[] arr = {1, 2, 3};
System.out.println(arr[2]);
// System.out.println(arr[3]); // Operation error , Termination of procedure
/** 2. Null pointer exception : NullPointerException. There is no problem with direct output . However, the function of calling a variable with a null pointer will report an error !! */
String name = null;
System.out.println(name); // null
// System.out.println(name.length()); // Operation error , Termination of procedure
/** 3. Type conversion exception :ClassCastException. */
Object o = 23;
// String s = (String) o; // Operation error , Termination of procedure
/** 5. Abnormal mathematical operation :ArithmeticException. */
//int c = 10 / 0;
/** 6. The digital conversion is abnormal : NumberFormatException. */
//String number = "23";
String number = "23aabbc";
Integer it = Integer.valueOf(number); // Operation error , Termination of procedure
System.out.println(it + 1);
System.out.println(" Program end .....");
}
}
summary :
Characteristics of runtime exceptions :
Runtime exception : Inherited from RuntimeException Or its subclasses , No error during compilation , The operation may report an error .
1.3 Common compile time exceptions
Compile time exception
No RuntimeException Or an exception of its subclass , An error is reported at the compile level , Must handle , Otherwise, the code will not pass .
Compile time exception example
What are the functions of compile time exceptions :
Is worried that the programmer's technology is not good , An error occurs during the compilation phase , The purpose is to remind not to make mistakes !
When encountering an exception, it is impossible to compile . When you meet me, you will meet me .
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
The goal is : Common compile time exceptions .
Compile time exception : Inherited from Exception Or its subclasses , No inheritance RuntimeException
" The exception at compile time is that an error will be reported at compile time ",
Must be handled by the programmer at the compile stage . Otherwise, the code compilation will report an error !!
What are the functions of compile time exceptions :
Is worried that the programmer's technology is not good , An error occurs during the compilation phase , The purpose is to remind !
Remind the programmer that this is likely to go wrong , Please check and be careful not to bug.
When encountering an exception, it is impossible to compile . When you meet me, you will meet me .
understand :
*/
public class ExceptionDemo {
public static void main(String[] args) throws ParseException {
String date = "2015-01-12 10:23:21";
// Create a simple date formatting class :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
// Parse the string time to become a date object
Date d = sdf.parse(date);
//
System.out.println(d);
}
}
summary :
Features of compile time exceptions
Compile time exception : Inherited from Exception Or its subclasses
An error is reported during compilation , Must handle , Otherwise, the code will not pass .
2.4 The default processing flow of exceptions
1. By default, an exception object will be automatically created in the exception code :ArithmeticException.
2. An exception is thrown to the caller from the point in the method , The caller eventually throws to JVM virtual machine .
3. After the virtual machine receives the exception object , First, output the exception stack information data directly on the console .
4. Kill the current program directly from the currently executed exception point .
5. Subsequent code has no chance to execute , Because the program is dead .
/**
The goal is : The default processing procedure for exception generation is parsing .( Automatic processing process !)
(1) By default, an exception object will be automatically created in the exception code :ArithmeticException.
(2) An exception is thrown to the caller from the point in the method , The caller eventually throws to JVM virtual machine .
(3) After the virtual machine receives the exception object , First, output the exception stack information data directly on the console .
(4) Kill the current program directly from the currently executed exception point .
(5) Subsequent code has no chance to execute , Because the program is dead .
Summary :
Once an exception occurs , The exception object is automatically created , Finally thrown to the virtual machine , virtual machine
As long as you receive an exception , Just output the exception information directly , Kill the program !!
The default exception handling mechanism is not good , Once something really goes wrong , The program immediately died !
*/
public class ExceptionDemo {
public static void main(String[] args) {
System.out.println(" Program starts ..........");
chu(10, 0);
System.out.println(" Program end ..........");
}
public static void chu(int a , int b){
System.out.println(a);
System.out.println(b);
int c = a / b;
System.out.println(c);
}
}
summary :
Default exception handling mechanism .
The default exception handling mechanism is not good , Once something really goes wrong , The program immediately died !
2.6 Compile time exception handling mechanism
There are three types of exception handling at compile time :
An exception is thrown directly to the caller , The caller also continues to throw out .
If an exception occurs, you can catch and handle it yourself , Don't bother others .
Combination of the first two , An exception is thrown directly to the caller , Caller capture processing .
Exception handling 1 —— throws
throws: Used in methods , You can throw the exception inside the method to the caller of this method .
This is not a good way , The method with exception does not handle the exception itself , If the exception is finally thrown to the virtual machine, it will cause the program to die .
Throw exception format :
Standard practice :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
The goal is : Compile time exception handling method 1 .
Compile time exception : Errors are reported at compile time , It must be handled by programmers , Otherwise, the code cannot pass !!
Throw exception format :
Method throws abnormal 1 , abnormal 2 , ..{
}
Suggest ways to throw exceptions : Means you can throw all exceptions ,
Method throws Exception{
}
Mode one :
Where compile time exceptions occur, throw the exceptions to the caller layer by layer , The caller eventually throws to JVM virtual machine .
JVM The virtual machine outputs exception information , Just kill the program , This method is the same as the default method .
Although it can solve code compilation errors , But once an exception occurs at runtime , The program will still die immediately !
This is not a good way !
Summary :
When an exception occurs in the mode, it runs out to the virtual machine layer by layer , If the final program is really abnormal , The program still dies immediately ! This way is not good !
*/
public class ExceptionDemo01 {
// public static void main(String[] args) throws ParseException, FileNotFoundException {
// System.out.println(" Program starts .....");
// parseTime("2011-11-11 11:11:11");
// System.out.println(" Program end .....");
// }
//
// public static void parseTime(String date) throws ParseException, FileNotFoundException {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
// Date d = sdf.parse(date);
// System.out.println(d);
//
// InputStream is = new FileInputStream("E:/meinv.jpg");
// }
public static void main(String[] args) throws Exception {
System.out.println(" Program starts .....");
parseTime("2011-11-11 11:11:11");
System.out.println(" Program end .....");
}
public static void parseTime(String date) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(date);
System.out.println(d);
InputStream is = new FileInputStream("E:/meinv.jpg");
}
}
Exception handling 2 —— try…catch…
Monitor and catch exceptions , Used inside the method , You can directly capture and handle the exceptions inside the method .
This way, you can , The method with exception handles the exception independently , The program can continue to execute .
Format :
Suggested format :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
The goal is : Compile time exception handling method 2 .
Mode two : Handle the exception by yourself , Who appears and who handles .
The format of catching and handling exceptions by yourself : Capture processing
try{
// Monitor code that may have exceptions !
}catch( Exception types 1 Variable ){
// Handling exceptions
}catch( Exception types 2 Variable ){
// Handling exceptions
}...
Monitor, capture and handle exceptions enterprise level writing :
try{
// Code with possible exception !
}catch (Exception e){
e.printStackTrace(); // Print exception stack information directly
}
Exception You can capture and handle all exception types !
Summary :
The second way , Can handle exceptions , And the code will not die after an exception .
This kind of scheme is still possible .
But in theory , This is not the best way , The upper caller cannot directly know the execution of the lower layer !
*/
public class ExceptionDemo02 {
public static void main(String[] args) {
System.out.println(" Program starts ....");
parseTime("2011-11-11 11:11:11");
System.out.println(" Program end ....");
}
public static void parseTime(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
Date d = sdf.parse(date);
System.out.println(d);
InputStream is = new FileInputStream("E:/meinv.jpg");
} catch (Exception e) {
e.printStackTrace(); // Print exception stack information
}
}
// public static void parseTime(String date) {
// try {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
// Date d = sdf.parse(date);
// System.out.println(d);
//
// InputStream is = new FileInputStream("E:/meinv.jpg");
// } catch (FileNotFoundException|ParseException e) {
// e.printStackTrace(); // Print exception stack information
// }
// }
// public static void parseTime(String date) {
// try {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
// Date d = sdf.parse(date);
// System.out.println(d);
//
// InputStream is = new FileInputStream("E:/meinv.jpg");
// } catch (FileNotFoundException e) {
// e.printStackTrace(); // Print exception stack information
// } catch (ParseException e) {
// e.printStackTrace();
// }
// }
// public static void parseTime(String date) {
// try {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM-dd HH:mm:ss");
// Date d = sdf.parse(date);
// System.out.println(d);
// } catch (ParseException e) {
// // There's a problem with parsing
// System.out.println(" There is a parsing time exception , Go snack !!");
// }
//
// try {
// InputStream is = new FileInputStream("E:/meinv.jpg");
// } catch (FileNotFoundException e) {
// System.out.println(" Your files are not available at all , Don't lie to me !!");
// }
// }
}
Exception handling 3 —— Combination of the first two
Method directly passes the difference through throws Throw it to the caller
After receiving the exception, the caller directly captures and handles it .
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
The goal is : Compile time exception handling method 3 .
Mode three : Throw the exception layer by layer to the outermost caller where the exception occurs ,
The outermost caller centralized capture processing !!( Standard practice )
Summary :
Compile time exception handling method 3 : The exceptions in the bottom layer are thrown to the outermost caller for centralized capture and processing .
The outermost caller of this scheme can know the underlying implementation , At the same time, the program will not die immediately after an exception , This is a
The best solution in theory .
Although exceptions can be handled in three ways , But as long as you can solve your problems in development , Each method may also use !!
*/
public class ExceptionDemo03 {
public static void main(String[] args) {
System.out.println(" Program starts ....");
try {
parseTime("2011-11-11 11:11:11");
System.out.println(" Function operation succeeded ~~~");
} catch (Exception e) {
e.printStackTrace();
System.out.println(" Function operation failed ~~~");
}
System.out.println(" Program end ....");
}
public static void parseTime(String date) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy、MM-dd HH:mm:ss");
Date d = sdf.parse(date);
System.out.println(d);
InputStream is = new FileInputStream("D:/meinv.jpg");
}
}
summary :
Summary of exception handling
According to the specification, the third way is the best in development : The bottom exception is thrown to the outermost layer , The outermost centralized capture processing .
Practical application , As long as the code can be compiled , And the function can complete , Then every exception handling method seems to be ok .
2.6 The handling mechanism of runtime exceptions
The handling form of runtime exception
Run time exception, no error in the compilation phase , Only when running can errors occur , Therefore, the compilation stage can not handle .
Follow the recommendations of the specification or deal with : It is recommended to capture and process in the outermost layer .
/**
The goal is : The handling mechanism of runtime exceptions .
Can be left alone , There is no error in the compilation stage .
According to the theoretical rules : It is suggested to deal with , Just capture and process at the outermost layer
*/
public class Test {
public static void main(String[] args) {
System.out.println(" Program starts ..........");
try {
chu(10, 0);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" Program end ..........");
}
public static void chu(int a , int b) { // throws RuntimeException{
System.out.println(a);
System.out.println(b);
int c = a / b;
System.out.println(c);
}
}
2.7 Cases where exception handling makes code more robust
Case study :
demand :
Enter a reasonable price with the keyboard ( It must be a number , Value must be greater than 0).
analysis : Define a dead cycle , Let users constantly input prices .
import java.util.Scanner;
/**
demand : You need to enter a legal price until Ask for a price greater than 0
*/
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println(" Please enter your legal price :");
String priceStr = sc.nextLine();
// convert to double Type of price
double price = Double.valueOf(priceStr);
// Judge whether the price is greater than 0
if(price > 0) {
System.out.println(" pricing :" + price);
break;
}else {
System.out.println(" The price must be positive ~~~");
}
} catch (Exception e) {
System.out.println(" There is something wrong with the data entered by the user , Please enter a legal value , A positive number is recommended ~~");
}
}
}
}
2.8 Custom exception
The need for custom exceptions ?
Java Can't provide exception classes for all the problems in the world .
If an enterprise wants to manage a business problem in an abnormal way , You need to customize the exception class .
Custom exception benefits :
You can use an exception mechanism to manage business problems , For example, remind the programmer to pay attention to .
At the same time, once it appears bug, You can clearly point out the error in the form of exception .
Custom exception classification
1、 Custom compile time exception
Define an exception class inheritance Exception.
Rewrite the constructor .
Use... Where there are exceptions throw new Custom object throw ,
effect : The compile time exception is that an error is reported at the compile time , The reminder is stronger , It must be handled !!
2、 Custom runtime exception
Define an exception class inheritance RuntimeException.
Rewrite the constructor .
Use... Where there are exceptions throw new Custom object throw !
effect : The reminder is not strong , No error during compilation !! Only when running can !!
/**
Custom compile time exception
1、 Inherit Exception
2、 Rewrite the constructor
*/
public class ItheimaAgeIlleagalException extends Exception{
public ItheimaAgeIlleagalException() {
}
public ItheimaAgeIlleagalException(String message) {
super(message);
}
}
/**
Custom compile time exception
1、 Inherit RuntimeException
2、 Rewrite the constructor
*/
public class ItheimaAgeIlleagalRuntimeException extends RuntimeException{
public ItheimaAgeIlleagalRuntimeException() {
}
public ItheimaAgeIlleagalRuntimeException(String message) {
super(message);
}
}
/**
The goal is : Custom exception ( understand )
introduce :Java A class has been designed to represent all possible exceptions in development .
But in actual development , There can be an infinite number of exceptions ,Java Unable to
All exceptions in the world define a representative class .
If an enterprise wants to define a certain business problem as an exception
You need to define your own exception class .
demand : I think I am younger than 0 year , Greater than 200 Age is an anomaly .
Custom exception :
Custom compile time exception .
a. Define an exception class inheritance Exception.
b. Rewrite the constructor .
c. Use... Where there are exceptions throw new Custom object throw !
The compile time exception is that an error is reported at the compile time , The reminder is stronger , It must be handled !!
Custom runtime exception .
a. Define an exception class inheritance RuntimeException.
b. Rewrite the constructor .
c. Use... Where there are exceptions throw new Custom object throw !
The reminder is not strong , No error during compilation !! Only when running can !!
*/
public class ExceptionDemo {
public static void main(String[] args) {
// try {
// checkAge(-34);
// } catch (ItheimaAgeIlleagalException e) {
// e.printStackTrace();
// }
try {
checkAge2(-23);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkAge2(int age) {
if(age < 0 || age > 200){
// Throw an exception object to the caller
// throw : Create an exception object directly inside the method , And throw... From this point
// throws : Used in method declarations , Throw an exception inside the method
throw new ItheimaAgeIlleagalRuntimeException(age + " is illeagal!");
}else {
System.out.println(" Legal age : Recommend goods to buy ~~");
}
}
public static void checkAge(int age) throws ItheimaAgeIlleagalException {
if(age < 0 || age > 200){
// Throw an exception object to the caller
// throw : Create an exception object directly inside the method , And throw... From this point
// throws : Used in method declarations , Throw an exception inside the method
throw new ItheimaAgeIlleagalException(age + " is illeagal!")
}else {
System.out.println(" Legal age : Recommend goods to buy ~~");
}
}
边栏推荐
- 资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
- Meet in the middle
- Lldp compatible CDP function configuration
- In rails, when the resource creation operation fails and render: new is called, why must the URL be changed to the index URL of the resource?
- JTAG debugging experience of arm bare board debugging
- golang中的WaitGroup实现原理
- SuperSocket 1.6 创建一个简易的报文长度在头部的Socket服务器
- 阿里云中mysql数据库被攻击了,最终数据找回来了
- 分享一个通用的so动态库的编译方法
- Deep learning framework TF installation
猜你喜欢
go-zero微服务实战系列(九、极致优化秒杀性能)
[100 cases of JVM tuning practice] 05 - Method area tuning practice (Part 2)
资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
[HFCTF2020]BabyUpload session解析引擎
Can the system hibernation file be deleted? How to delete the system hibernation file
UI control telerik UI for WinForms new theme - vs2022 heuristic theme
2022 Google CTF SEGFAULT LABYRINTH wp
"Exquisite store manager" youth entrepreneurship incubation camp - the first phase of Shunde market has been successfully completed!
第三方跳转网站 出现 405 Method Not Allowed
Body mass index program, entry to write dead applet project
随机推荐
boot - prometheus-push gateway 使用
Segmenttree
taro3.*中使用 dva 入门级别的哦
云呐|工单管理软件,工单管理软件APP
mysql: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such
Taro中添加小程序 “lazyCodeLoading“: “requiredComponents“,
from .cv2 import * ImportError: libGL.so.1: cannot open shared object file: No such file or direc
Come on, don't spread it out. Fashion cloud secretly takes you to collect "cloud" wool, and then secretly builds a personal website to be the king of scrolls, hehe
微信公众号发送模板消息
2022 Google CTF SEGFAULT LABYRINTH wp
Neon Optimization: an optimization case of log10 function
[batch dos-cmd command - summary and summary] - jump, cycle, condition commands (goto, errorlevel, if, for [read, segment, extract string]), CMD command error summary, CMD error
"Exquisite store manager" youth entrepreneurship incubation camp - the first phase of Shunde market has been successfully completed!
[Niuke] [noip2015] jumping stone
Metauniverse urban legend 02: metaphor of the number one player
Implementation principle of waitgroup in golang
ARM裸板调试之JTAG原理
MySQL中回表的代价
云呐-工单管理制度及流程,工单管理规范
HMM 笔记