Exception and capture in Java, custom exception

insert image description here

1. Exception overview

1.1 What is a program exception

 In the process of project development using computer language, even if the programmer writes the code perfectly, some problems will still be encountered during the operation of the system, because many problems cannot be avoided by code.

Exception : Refers to the abnormal situation that occurs during the execution of the program. If it is not handled, it will eventually lead to the abnormal stop of the JVM.

Exceptions do not refer to syntax errors and logic errors. If the syntax is wrong, the compilation will not pass, no bytecode file will be generated, and it will not run at all. The logic of the code is wrong, but the desired result is not obtained, for example: to find the sum of a and b, you wrote ab.

1.2 Exception throwing mechanism

 In Java, different exceptions are represented by different classes. Once an exception occurs, an object of the exception type is created and thrown ( throw). Then programmers can catch ( catch) this exception object and handle it; if this exception object is not caught (catch), then this exception object will cause the program to terminate.

The simulation program will generate an ArrayIndexOfBoundsException (ArrayIndexOfBoundsException):

public class ArrayTools {
    
    
    // 对给定的数组通过给定的角标获取元素。
    public static int getElement(int[] arr, int index) {
    
    
        int element = arr[index];
        return element;
    }
}

//测试类
public class ExceptionDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
     34, 12, 67 };
        intnum = ArrayTools.getElement(arr, 4)
        System.out.println("num=" + num);
        System.out.println("over");
    }
}

Diagram of the execution process of the above program:

insert image description here

1.3 How to treat exceptions

 There are generally two solutions to the exceptions that occur in the program: one is to terminate the operation of the program when an error is encountered. Another method is that programmers fully consider various possible exceptions and errors when writing programs, and try their best to prevent and avoid them. It is really unavoidable, to write the corresponding code for exception detection, and exception handling, to ensure the robustness of the code .

2. Java exception system

2.1 Throwable

Common methods in Throwable:

  • public void printStackTrace(): Print the details of the exception.

Contains the type of exception, the cause of the exception, the location of the exception, and must be used in the development and debugging phases printStackTrace.

  • public String getMessage(): Get the reason for the exception.

2.2 Error 和 Exception

ThrowableCan be divided into two categories: Errorand Exception. Corresponding java.lang.Errorto java.lang.Exceptiontwo classes respectively.

Error : A serious problem that the Java Virtual Machine cannot resolve. Such as: JVM system internal errors, resource exhaustion and other serious situations. Generally do not write targeted code for processing.

  • For example: StackOverflowError (stack memory overflow) and OutOfMemoryError (heap memory overflow, OOM for short).

Exception : Other general problems caused by programming errors or accidental external factors need to be handled with specific codes to keep the program running. Otherwise, once an exception occurs, the program will also hang up.

  • null pointer access
  • An attempt was made to read a file that does not exist
  • network connection lost
  • Array subscript out of bounds

illustrate:

  • Whether it is Error or Exception, there are many subclasses, and the types of exceptions are very rich. When the code runs abnormally, especially when we are not familiar with the exception, don't be nervous, find the class name of the exception in the corresponding API to understand what type of exception it is.

2.3 Compile-time exceptions and runtime exceptions

The execution of a Java program is divided into a compile-time process and a run-time process. Some errors only occur at runtime.

insert image description here

According to the stage in which the abnormality may appear, the abnormality can be divided into:

  • Compile-time exceptions (that is, checked exceptions, checked exceptions): During the code compilation phase, the compiler can clearly warn that the current code may (not necessarily) xx exceptions occur, and clearly urge programmers to write code to handle it in advance. If the programmer does not write the corresponding exception handling code, the compiler will directly determine that the compilation failed, so that the bytecode file cannot be generated. Usually, the occurrence of this type of exception is not caused by the programmer's code, or it cannot be avoided by adding simple judgments, for example: FileNotFoundException (file not found exception).
  • Runtime exceptions (i.e. runtime exceptions, unchecked exceptions, and unchecked exceptions): During the code compilation phase, the compiler does not check at all, and the compiler does not give any hints whether the exception will occur or not. It can't be found until the code runs and the xx exception does occur. Usually, this kind of exception is caused by the programmer's poorly written code, which can be avoided with a little judgment or careful inspection.
    • java.lang.RuntimeException: class and its subclasses are runtime exceptions. For example: ArrayIndexOutOfBoundsException: array subscript out of bounds exception, ClassCastExceptiontype conversion exception.

insert image description here

3. Common errors and exceptions

3.1 Error

Most commonly VirtualMachineError, it has two classic subclasses: StackOverflowError, OutOfMemoryError.

@Test
public void test01(){
    
    
    //StackOverflowError
    recursion();
}

public void recursion(){
    
     //递归方法
    recursion(); 
}
@Test
public void test02(){
    
    
    //OutOfMemoryError
    //方式一:
    int[] arr = new int[Integer.MAX_VALUE];
}

3.2 Runtime exceptions

@Test
public void test05(){
    
    
    int a = 1;
    int b = 0;
    //ArithmeticException
    System.out.println(a/b);
}

3.3 Compile-time exceptions

@Test
public void test06() {
    
    
    Thread.sleep(1000);//休眠1秒  InterruptedException
}

4. Exception handling

4.1 Overview of Exception Handling

 When writing a program, it is often necessary to add detection codes where errors may occur. For example, when performing x/y operations, it is necessary to detect that the denominator is 0, the data is empty, and the input is not data but characters. Too many if-else branches will lead to lengthened, bloated program code, and poor readability, and programmers need to spend a lot of energy "plugging loopholes". Therefore, an exception handling mechanism is adopted.

Java exception handling:

The exception handling mechanism adopted by Java is to gather the exception handling program code together and separate it from the normal program code, making the program concise, elegant and easy to maintain.

Java exception handling method:

Method 1: try-catch-finally
Method 2: throws + exception type

4.2 Catch exceptions (try-catch-finally)

Java provides a catch-and-throw model for exception handling.

  • If an exception occurs during the execution of a Java program, an exception class object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing ( ) throwexception.
  • If an exception is thrown in a method, the exception object will be thrown to the caller method for processing. If the exception is not handled in the calling method, it continues to be thrown to the upper method of the calling method. This process will continue until the exception is handled. This process is called catching ( catch) the exception.
  • If an exception returns to main()the method, and main() does not handle it, program execution terminates.

4.2.1 Basic format of try-catch-finally

try{
    
    
	......	//可能产生异常的代码
}
catch( 异常类型1 e ){
    
    
	......	//当产生异常类型1型异常时的处置措施
}
catch( 异常类型2 e ){
    
    
	...... 	//当产生异常类型2型异常时的处置措施
}  
finally{
    
    
	...... //无论是否发生异常,都无条件执行的语句
} 

1. The overall execution process:

When an exception may occur in a certain piece of code, whether the exception is a compile-time exception (checked exception) or a runtime exception (unchecked exception), we can use try blocks to enclose it, and write branches below the block to try to trycatch catchThe corresponding exception object.

  • If no exception occurs in the code in the try block when the program is running, then all branches of the catch will not be executed.
  • If an exception occurs in the code in the try block when the program is running, according to the type of the exception object, the first matching catch branch will be selected from top to bottom for execution. At this time, the code below the statement where the exception occurs in the try will not be executed, and the code after the entire try...catch can continue to run.
  • If an exception occurs in the code in the try block when the program is running, but none of the catch branches can match (catch) the exception, then the JVM will terminate the execution of the current method and "throw" the exception object to the caller. If the caller doesn't handle it, the program hangs.

insert image description here

2、try:

The first step in catching exceptions is to use try{…}a statement block to select the scope of catching exceptions, and place the business logic code that may cause exceptions in the try statement block.

3、catch (Exceptiontype e)

  • catchThe branch is divided into two parts, catch()the exception type and exception parameter name are written in the middle, and {}the code of what to do if this exception occurs is written in the middle.
  • If you know exactly what kind of exception is generated, you can use the exception class as the parameter of catch; you can also use its parent class as the parameter of catch.
    For example: where a class can be used ArithmeticExceptionas a parameter, the class can be used RuntimeExceptionas a parameter, or the parent Exceptionclass of all exceptions can be used as a parameter. But it cannot be ArithmeticExceptionan exception that has nothing to do with the class, such as NullPointerException(the statement in the catch will not be executed).
  • Each try statement block can be accompanied by one or more catch statements to handle different types of exception objects that may be generated.
  • If there are multiple catch branches, and multiple exception types have a parent-child relationship, it must be ensured that the smaller child exception type is on top and the larger parent exception type is on the bottom. Otherwise, report an error.
  • Common exception handling methods in catch
    • public String getMessage(): Get the description information of the exception and return a string
    • public void printStackTrace(): Print the exception trace stack information and output to the console. It contains the type of exception, the cause of the exception, and the location where the exception occurred. In the development and debugging stages, printStackTrace() must be used.

insert image description here

4.2.2 Finally usage and examples

insert image description here

  • Because the exception will cause the program to jump, which will cause some statements to not be executed. And there are some specific codes in the program that need to be executed regardless of whether an exception occurs. For example, database connection, input stream output stream, Socket connection, Lock lock closing, etc., such codes are usually placed in the finally block. Therefore, we usually declare the code that must be executed in finally.
    • The only exception is to use System.exit(0) to terminate the currently running Java virtual machine.
  • Regardless of whether an abnormal event occurs in the try code block, whether the catch statement is executed, whether there is an exception in the catch statement, or whether there is a return in the catch statement, the statements in the finally block will be executed.
  • The finally statement and the catch statement are optional, but finally cannot be used alone.

4.3 Declare throwing exception type (throws)

 If when writing the code of the method body, a certain line of code may have a compile-time exception, and the compilation fails if it is not processed, but it may not be suitable for processing in the current method body or a reasonable processing method cannot be given, then this method should display Exceptions are thrown, indicating that the method will not handle these exceptions, and the caller of the method is responsible for handling them.

insert image description here

Specific method: Use the throws statement in the method declaration to declare the list of thrown exceptions. The exception type behind throws can be the exception type generated in the method, or its parent class.

4.3.1 basic format of throws

Declaration exception format:

Modifier return value type method name (parameter) throws exception class name 1, exception class name 2... { }
Multiple exception types can be written after throws, separated by commas.

public void readFile(String file)  throws FileNotFoundException,IOException {
    
    
	...
	// 读文件的操作可能产生FileNotFoundException或IOException类型的异常
	FileInputStream fis = new FileInputStream(file);
    //...
}

throwsYou can also write the runtime exception type later, but the runtime exception type, writing or not writing has no difference for the compiler and program execution. If it is written, the only difference is that after the caller calls the method, when using the try...catch structure, IDEA can obtain more information and which catchbranch needs to be added.

4.3.2 Requirements for throws in method rewriting

When the method is overridden:

(1) Method names must be the same
(2) Formal parameter lists must be the same
(3) Return value types

  • Primitive data types and void: must be the same
  • Reference data type: <=

(4) Permission modifier: >=, and requires the overridden method of the parent class to be visible in the subclass
(5) Cannot be static, finalthe modified method

For throws exception list requirements:

  • If there is no "throws compile-time exception type" after the method signature of the overridden method of the parent class, then when the method is rewritten, "throws compile-time exception type" cannot appear after the method signature.
  • If the method signature of the overridden method of the parent class is followed by "throws compile-time exception type", then when the method is overridden, the compile-time exception type of throws must be <= the compile-time exception type of the overridden method throws, or compile without throws abnormal.
  • Method override, no requirement for "throws runtime exception type".

4.4 Choice of two exception handling methods

For exceptions, use appropriate handling. The exception at this time mainly refers to the compile-time exception

  • If the program code involves resource calls (streams, database connections, network connections, etc.), you must consider using them to try-catch-finallyensure that no memory leaks occur.
  • If the overridden method of the parent class does not have throwsan exception type, if an exception occurs in the overridden method of the subclass, it can only be considered for handling try-catch-finally, not throws.
  • During development, methods b, c, and d are called in sequence in method a, and the relationship between methods b, c, and d is progressive. At this point, if there are exceptions in methods b, c, and d, we usually choose to use throws, while in method a we usually choose to use try-catch-finally.

5. Manually throw an exception object: throw

There are two ways to generate exception objects in Java:

  • Automatically generated by the virtual machine : During the running of the program, if the virtual machine detects that there is a problem with the program, then for the current code, an instance object corresponding to the exception class will be automatically created in the background and thrown.

  • Manually created by the developer : new exception type ([actual parameter list]);, if the created exception object does not throw, it will have no impact on the program, just like creating a normal object, but once throw is thrown, it will have no impact on the program Operation has an impact.

5.1 Usage format

throw new 异常类名(参数);

The exception object thrown by the throw statement is the same as the exception object automatically created and thrown by the JVM.

  • If it is an object of an exception type at compile time, it also needs to use throws or try...catch to handle it, otherwise the compilation will fail.
  • If it is an object of runtime exception type, the compiler does not prompt.
  • An exception that can be thrown must be Throwablean instance of or a subclass of it.

5.2 Notes on use

Whether it is an object of an exception type at compile time or an object of an exception type at runtime, if it is not try..catchproperly handled, it will cause the program to crash.

The throw statement will cause the program execution flow to be changed. The throw statement explicitly throws an exception object, so the code below it will not be executed .

If the current method does not have a try...catch to handle the exception object, the throw statement will replace the return statement to terminate the execution of the current method in advance and return an exception object to the caller.

6. Custom exceptions

6.1 Why do you need a custom exception class

 Different exception classes in Java represent a specific abnormal situation. Then in development, there are always some exceptions that are not defined in the core class library. At this time, we need to define exception classes related to the business according to the exceptions of our own business.

6.2 How to customize exception class

(1) To inherit an exception type

Customize a compile-time exception type: the custom class inherits java.lang.Exception.
Customize a runtime exception type: the custom class inherits java.lang.RuntimeException.

(2) It is recommended to provide at least two constructors, one is a no-argument constructor and the other is a (String message) constructor.

(3) Custom exceptions need to provide serialVersionUID

6.3 Notes

  1. Custom exceptions can only be thrown through throw.
  2. The most important thing about custom exceptions is the name and message attribute of the exception class. When an exception occurs, the exception type can be judged based on the name. For example: TeamException("The member is full and cannot be added");
  3. Custom exception objects can only be thrown manually. After throwing, it is handled by try...catch, or throws can be handled by the caller.

Example:

//自定义异常:
public class NotTriangleException extends Exception{
    
    
    static final long serialVersionUID = 13465653435L;

    public NotTriangleException() {
    
    
    }

    public NotTriangleException(String message) {
    
    
        super(message);
    }
}
//手动抛出异常对象
throw new NotTriangleException("输入数据不正确");

7. Summary

Exception handling 5 keywords:

insert image description here

The farthest distance in the world is when I am in the if and you are in the else, it seems that we are always together and separated forever; the
most infatuated waiting in the world is when I am a case and you are a switch, maybe you will never be able to choose yourself;
In true love, you are trying and I am catching. No matter you lose your temper, I will bear it silently and deal with it quietly. Until then, come and look forward to our finally.

Guess you like

Origin blog.csdn.net/weixin_43847283/article/details/130177609