A detailed summary of Exception handling in Java-programs

1. Exception overview:

In the Java language, abnormal situations that occur during program execution are called "abnormalities". (Syntax errors and logic errors in the development process are not abnormal).
Two situations that occur during the execution of a Java program are:

  1. Error: A serious problem that cannot be solved by the Java virtual machine. Such as JVM internal errors, resource exhaustion ( StackOverflowError, OOM, etc. ), etc. Generally do not write targeted code processing.
  2. Exception: Other general problems caused by programming errors or accidental external factors can be handled with the targeted code. For example: null pointer abnormality, network connection interruption, search for non-existent files, array corner mark out of bounds, etc.
  3. Exception is subdivided: it is divided into compile-time exceptions (check): such as IOException, FileNotFoundException, ClassNotFoundException, etc. and runtime exceptions (uncheck, RuntimeException) such as: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException, InputMismatchException, ArithmeticException, etc.

Two, 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. The program is concise, elegant, and easy to maintain.
Java provides a catch-and-throw model for exception handling. If an exception occurs during program execution, an exception class object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing an exception .

① "Throwing" exceptions.
Among them, the generation of abnormal objects is divided into automatic generation and manual creation :

  • Automatically generated by the virtual machine : During the running of the program, the virtual machine detects that there is a problem with the program. If the corresponding handler is not found in the current code, it will automatically create an instance object corresponding to the exception class in the background and throw it- Automatically throw .
  • Manually created by the developer: Exception exception = new ClassCastException(); If the created exception object is not thrown, it has no effect on the program, just like creating an ordinary object. Once thrown, the following code will not be executed! !

Exception handling method 1:
② "Catch"-handle exceptions

try{
    
    
	//可能出现异常的代码
}catch(异常类型1 变量名1){
    
    
	//处理异常的方式1
}catch(异常类型2 变量名2){
    
    
	//处理异常的方式2
}catch(异常类型3 变量名3){
    
    
	//处理异常的方式3
}
...
//可以根据需要添加处理异常的方式,catch的效果相当于switch()里的case
finally{
    
    
	//一定会执行的代码
}

Description:

  1. Finally is optional.
  2. What is declared in finally is the code that will be executed. Even if the catch is abnormal again, there is a return statement in the try and a return statement in the catch.
  3. Resources such as database connections, input and output streams, and network programming sockets cannot be automatically recycled by the JVM. We need to manually release the resources by ourselves. The release of resources at this time needs to be declared in finally.
  4. Use try to wrap the possible exception code. In the execution process, once an exception occurs, an object corresponding to the exception class will be generated. According to the type of this object, go to catch for matching.
  5. Once the exception object in the try matches a certain catch, it enters the catch for exception handling. Once the processing is completed, jump out of the current try-catch structure (in the absence of finally written), continue to execute the following code.
  6. If the exception type in catch has no child-parent relationship, it doesn't matter who declares on the top and who declares on the bottom.
  7. If the exception type in catch has a child-parent relationship, the child must be declared above the parent, otherwise an error will be reported.
  8. Commonly used exception object handling methods: ①String getMessage() ②printStackTrace().
  9. Variables declared in the try structure can no longer be called after the try structure is released.
  10. try-catch-finally structures can be nested within each other.

note:

  1. Use try-catch-fina to handle compile-time exceptions, so that the program no longer reports errors at compile time, but errors may still be reported at runtime. It is equivalent to using try-catch-finally to delay an exception that may occur at compile time until it appears at runtime.
  2. In development, because runtime exceptions are more common, we usually don't write try-catch-finally for runtime exceptions. For compile-time exceptions, we must consider the handling of exceptions, otherwise the code cannot run.

Exception handling method 2: throws + exception type

//throws直接声明在方法名后方
public void method() throws NullPointerException{
    
    
	int[] arr1 = null;
	System.out.println(arr[0]);
}
  1. "throws + exception type" is written in the method declaration. Indicate the type of exception that may be thrown when this method is executed. Once an exception occurs when the method body is executed, an object of the exception class will still be generated at the exception code. When this object meets the exception type after throws, it will be thrown. The code following the exception code will no longer be executed! !
  2. Note: The method of throws only throws the exception to the caller of the method, and does not actually handle the exception. try-catch-finally is really the exception handling.

How to choose try-catch-finally or throws in development?

  1. If the overridden method in the parent class does not have the throws method to handle exceptions, the method overridden by the subclass cannot use throws, which means that if there is an exception in the method overridden by the subclass, it must be handled in the try-catch-finally method.
  2. In the executed method a, several other methods are called successively, and these methods are executed in a progressive relationship. We recommend that these methods use throws for processing. The execution method a can consider the try-catch-finally method for processing.
throw new Exception("您输入的数据非法!");

Three, exception examples

ArrayIndexOutOfBoundsException: Array corner mark out of bounds exception:

  • Reasonable range: [0,array.length-1];
  • 越界:array[-1]、array[length];

NullPointerException: Null pointer exception:
int[] arr = null;
arr[0];

  • 1. To call an element that is not in the array, and return a null pointer;
  • 2. Call the range over value in the array and return a null pointer.

Guess you like

Origin blog.csdn.net/qq_30068165/article/details/111998726
Recommended