Analysis of exceptions in java

Posted by foreknowapparel on Mon, 10 Jan 2022 20:03:29 +0100

1, What is an exception


Throwable is a special case in which the code does not meet the expectations

Classification and characteristics of anomalies

1. Classification

① Exceptions can be divided into errors and exceptions

② Errors are usually caused by syntax, logic or hardware problems

③ Exceptions are problems that arise in the running and configuration of programs

④ Exceptions can be subdivided into inspected exceptions (errors are reported when compiling) and non inspected exceptions (no errors are reported when compiling and errors are reported when running)

2. Necessity of abnormality

There are all kinds of unexpected situations in the code, and exceptions can maintain the stability of the program

2, Common exceptions

1. Arithmetic exception

It is usually because the operation logic is wrong, such as 0 as the divisor

2. Array index out of bounds exception (ArrayIndexOutOfBoundsException)

Usually, when using elements that exceed the length of the array, such as an array with a length of 2, and then assigning a value to the element with an array subscript of 3, the array will be reported as out of bounds

3. Null pointer exception

Call a method of an empty object, for example, call the equals method of an object with a null value to compare with another value (so when using the equals method to compare String values, the variable is usually written in the parentheses behind and the explicit value is written in the front)

4. Type conversion exception

For example, a subclass is strongly converted to a parent class

3, Resolve exception

1. Catch exception

The code statement after catching the exception runs normally. Catching the exception is usually used when you can solve the exception and need the subsequent code to run normally

Syntax format
    Possible exception codes
}catch(Exception type (exception name){
    Processing code

int[] nums=new int[2];
    nums[3]=15;//The array definition length is exceeded, which belongs to array index out of bounds ()
}catch(ArrayIndexOutOfBoundsException e){
    System.err.println("Array index exception")//err set the output font color to red

System.out.println("After catching exception")

2. When multiple exceptions are caught

public static void main(String[] args){

public static void test(String str){
        System.err.println(str.equals(""));//If the passed in parameter is null, the null pointer exception occurs
        int num=12/0;//Arithmetic anomaly
        System.out.println("try In code block")

/*If there are multiple exceptions in try, you can use | to write multiple exceptions in catch, not |, or you can directly use Exception to cover all exceptions*/
        }catch(NullPointerException  | ArithmeticException e){
            e.printStackTrace//Output exception information
            System.out.println("catch In code block")

Final result output:

Null pointer exception error
catch In code block
 Arithmetic operation error
catch In code block

Step analysis

① When the method is called for the first time, the passed in parameter is null, and the null pointer in the first line of code in try is abnormal

② Because the error is reported in the first line, other codes in the try code block after the error code are not executed, and jump to the catch code block to continue execution

③ In the second call, if the parameter passed in by the method is not empty, an arithmetic exception is reported in the second line, and the output statement in the third line is still not executed. Continue to jump to the catch code block to execute other codes

It can be seen that when multiple exceptions are caught, the code in the try code block will not be executed from the statement with exception to the end of the try code block, and the code behind the catch code block will not be affected

4, finally (note that it is not final)

1. Function

Ensure that the code in the finally code block will be executed

2. How to use

It is written after the catch code block. When there is no catch code block, it can be written directly after the try code block

3. Syntax format





5, Declare exception types (throws, you can declare multiple exception types at one time)

1. Definitions

The possible exceptions declared shall be solved by the upper layer. If the upper layer cannot solve them, they will continue to be declared to the upper layer until the end

Declare an exception. If it is not caught, the result will still report an error and stop the operation of subsequent code

2. Function

In order to enable the upper layer to catch exceptions, if an exception is not thrown, once the program makes an error, the upper layer does not know which part of the error is. It only knows that there is an error in one part and does not know how to solve it. If an exception is thrown, the upper layer code can know the problem code and handle it in time to avoid program crash

3. Cases

public class Demo1{
    /*3.After being thrown, you cannot continue to throw upward. The compiled error reporting program ends running, and other codes after the exception code do not run. Even if the finally code block is followed, it will not continue to execute*/

    public static void main(String[] args)throws Exception{
        //2. The caller needs to handle the exception. If not, continue to throw it up
    //4. The subsequent code will not be run, and the program has been ended
           int num=5/0;
       }catch(ArithmeticException e){
           //System.out.println("arithmetic exception");
           System.out.println("finally output");

//1.throws Exception throws up the possible exceptions    
    public static double total(int num)throws Exception{
            return num/0;   //Arithmetic anomaly

6, Throw exception object (only a single exception object can be thrown)

1. Definitions

Throw an exception by manually creating an object within a method

2. Syntax format

throw new exception type

3. Cases


    public static void main(String[] args) {
        int num=0;

    public static void total(int num){
        int num2=5/num;//Arithmetic exception when the passed in parameter is 0
        //throw new exception type ();
        throw new ArithmeticException("Divisor cannot be 0");

7, Custom exception

1. Syntax format

public class (class name + Exception) extends Exception(){

/ / parameterless construction method

public (class name + Exception) (){



/ / add a parameterized constructor with exception information

public (class name + Exception) (){




2. Precautions

  • The class name of a custom Exception is usually followed by an Exception to indicate that this is an Exception
  • Custom Exception must inherit Exception or RuntimeException
  • Inherited from the Exception description is an Exception that will report an error during compilation. The compilation time Exception must handle try or throws
  • The exception inherited from RuntimeException is a runtime exception that does not need to be handled. It is handed over to the virtual machine for processing and interrupt processing.
  • The exception information is output by passing parameters to the default parent class constructor super() in the constructor