Author: Rukawa Maple Knock Code
Blog Homepage: Rukawa Kaede's Blog
Column: Learn java with me
Quote: Stay hungry stay foolish
If you want to do good things, you must first sharpen your tools. Let me introduce you to a super powerful tool for winning offers from big manufacturers - Niuke.com
Article directory
1. The concept and architecture of exceptions
2. Array out of bounds exception
1.3 Classification of exceptions
2.2 Exception capture (throws and try-catch)
1. The concept and architecture of exceptions
1.1 The concept of exception
What is an exception?
In java, abnormal behaviors that occur during program execution are called exceptions
Different types of exceptions in java are described by their corresponding classes
Here are some common exceptions:
1. Arithmetic exception
public class Test {
public static void main(String[] args) {
System.out.println(10/0);
}
}
2. Array out of bounds exception
public class Test {
public static void main(String[] args) {
int[] arr = {0,1,2,3};
System.out.println(arr[100]);
}
}
3. Null pointer exception
public class Test {
public static void main(String[] args) {
int[] arr = null;
System.out.println(arr.length);
}
}
4. Input mismatch exception
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(n);
}
}
1.2 Exceptional Architecture
Throwable: is the top-level class of the exception system, which derives two important subclasses, Error and Exception
Error: Refers to serious problems that cannot be solved by the Java virtual machine, such as: JVM internal errors, resource exhaustion, etc. Typical representatives: StackOverflowError and OutOfMemoryError
Exception: After the exception is generated, the programmer can process it through the code, so that the program can continue to execute. The exception we usually call is Exception
1.3 Classification of exceptions
1. Compile-time exception
Exceptions that occur during program compilation, known as compile-time exceptions, also known as checked exceptions
If the program wants to compile, it must handle the exception before continuing to compile
class Person{
private String name;
private String gender;
int age;
//想要让该类支持深拷贝,覆写Object类的clone方法即可
public Person clone(){
return (Person)super.clone();
}
}
2. Runtime exception
Exceptions that occur during program execution, known as runtime exceptions, also known as unchecked exceptions
Runtime refers to the errors that occur during the execution of the program by the JVM after the program has been compiled to obtain the class file.
RunTimeException and the corresponding exceptions of its subclasses are called runtime exceptions. For example: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException
2. Exception handling
The five main keywords of exception handling: throw, try, catch, final, throws
2.1 throw exception throw
In Java, you can use the throw keyword to throw a specified exception object to inform the caller of the error message. The specific syntax is as follows
throw new XXXException("异常产生的原因");
Next we write a code that throws an exception
public class Test {
public static void main(String[] args) {
int[] arr = null;
test(arr);
}
public static void test (int[] arrays){
if(arrays == null){
throw new NullPointerException("传递的数组为null");
}
}
}
Precautions:
1. throw must be written inside the method body
2. The thrown object must be Exception or a subclass of Exception
3. If a RunTimeException or a subclass of RunTimeException is thrown, it can be handled directly by the JVM without processing it.
4. If a compile-time exception is thrown, the user must handle it, otherwise the compilation will fail.
5. Once the exception is thrown, the subsequent code will not be executed
2.2 Exception capture (throws and try-catch)
There are two main ways to capture exceptions, that is, the specific processing methods of exceptions: exception declaration throws and try-catch capture processing
exception declaration throws
The current method does not handle exceptions and reminds the caller of the method to handle exceptions
That is, when a compile-time exception is thrown in the method, and the user does not want to handle the exception, at this time, the exception can be thrown to the caller of the method with the help of throws.
语法格式:
修饰符 返回值 类型 方法名(参数列表) throws 异常类型1,异常类型2...{
//...
}
Precautions
1. throws must follow the method's parameter list
2. The declared exception must be a subclass of Exception or Exception
3. If multiple exceptions are thrown inside the method, throws must be followed by multiple exception types, separated by commas. If multiple exception types are thrown and have a parent-child relationship, you can directly declare the parent class
4. When calling a method declared to throw an exception, the caller must handle the exception, or continue to use throws to throw
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = null;
test(arr);
}
public static void test(int[] arrays) throws Exception{
if(arrays == null){
throw new NullPointerException();
}
}
}
When test only declares an exception but does not handle it, it will look up the caller, that is, the main function, and it does not handle it, then the JVM handles the exception.
try-catch catch and handle
throws does not really handle the exception, but reports the exception to the caller of the method that throws the exception, and the caller handles it. If you really want to handle exceptions, you need try-catch
Syntax format:
try {
//将可能出现异常的代码放在这里
//可能会抛出异常,也可能不会
}catch(要捕获的异常类型 e){
//如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类时,就会被捕获到
//对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
}
Precautions:
1. The code after the exception is thrown in the try block will not be executed
public class Test {
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
System.out.println("hello world");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
no output hello world
2. If the type of the exception thrown does not match the type of the exception at the time of the catch, that is, the exception will not be successfully caught and will not be processed, and continue to throw out until the JVM receives it and interrupts the program - the exception is based on the type. captured
The type of exception thrown does not match the type of exception when caught:
public class Test {
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
System.out.println("hello world");
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
3. Multiple different exception objects may be thrown in try, and multiple catches must be used to capture them—that is, multiple exceptions, multiple captures
public class Test {
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
System.out.println("hello world");
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
The handling of multiple exceptions is exactly the same, and can also be written as follows:
public class Test {
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
System.out.println("hello world");
} catch (ArithmeticException | NullPointerException |ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
There is a parent-child relationship between exceptions. The subclass exception must be caught in the front, and the parent class exception must be caught in the back, otherwise the syntax is wrong.
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
System.out.println("hello world");
} catch (ArithmeticException | NullPointerException |ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
Exception catches all exceptions
finally
Some specific codes need to be executed regardless of whether the program is abnormal or not; when the program exits normally or abnormally, resources must be recovered; exceptions may also cause program jumps, which may cause some statements to fail to be executed. You need to use the finally keyword
syntax format
try {
//...
}catch(要捕获的异常类型 e){
//...
}finally{
//此处的语句无论是否发生异常,都会被执行到
//如果没有抛出异常,或者异常被捕获处理了,这里的代码也会执行
}
public static void main(String[] args) throws Exception {
try {
int[] arr = null;
System.out.println(arr[3]);
} catch (ArithmeticException | NullPointerException |ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} finally {
System.out.println("hello world");
}
}
The timing of finally execution is before the method returns (if there is a return in try or catch, finally will be executed before the return). But if there is also a return statement in finally, then the return in finally will be executed, so that try will not be executed Zhongyuan's return
3. Summary
A program executes the code in the try first. If the code in the try has an exception, it will end the code in the try to see if it matches the exception type in the catch. If a matching exception type is found, the code in the catch is executed. If no matching exception type is found, the exception is passed up to the upper caller. The code in finally is executed (before the method ends) regardless of whether a matching exception type is found. If the upper-level caller does not handle the exception, it will continue to pass up until the main method has no suitable code to handle the exception, and it will be handed over to the JVM for processing, at which point the program will terminate abnormally.
"The sharing of this issue is here, remember to give the blogger a three-link, your support is the biggest driving force for my creation!