Basic knowledge of Java exception and handling in Java

catalogue

abnormal

1. Classification of anomalies

2. Two methods of handling exceptions

try...catch...finally

The difference between compile time exception and run-time exception:

Methods in Throwable

finally

throws

throw 

The difference between throws and throw:

abnormal

Abnormal condition in Java program

1. Classification of anomalies

Exception in Java: Throwable

Serious problems: we don't deal with errors. Such problems are usually very serious, such as memory overflow (OOM)

Problem: exceptions are divided into compile time exceptions and run-time exceptions

Compile time exceptions: all exceptions except runtimeexceptions are compile time exceptions that must be handled. If they are not handled, the program cannot be compiled and run

In general, we will not deal with the problem of exception when we are not strict in the process of running the code.

If there is a problem with the program and we don't do any processing, the JVM will eventually make the default processing and output the name of the exception, the relevant reason and the information of the problem on the console. At the same time, the program will stop and the subsequent code will not be executed.

Classification diagram of anomalies:

 

2. Two methods of handling exceptions

1,try...catch...finally

2,throws

try...catch...finally

try...catch...finally processing format:

try{
Code that may cause problems

}Catch (exception class name variable name){
Processing code for problems

}finally{
As long as the program goes smoothly, the content in finally will be executed anyway

}

Format deformation:

try{

Code that may cause problems

}Catch (exception class name variable name){

Processing code for problems

}

Note: the less code in try, the better; catch must have content, even if the content is just a simple prompt statement

Take divisor 0 as an example:

When 10 divided by 0 is directly output in the code, there will be no exception in compilation, but there will be exceptions in operation, that is, runtime exceptions.

Join try Catch handling exception:

public class Demo1 {
    public static void main(String[] args) {
        int a=10;
        int b=0;
        
        try{
            System.out.println(a / b);
        }catch (ArithmeticException e){
            System.out.println("The divisor is 0 and cannot be divided");
        }
    }
}

Output result:

The above is to deal with an exception. When dealing with two or more exceptions, there are two methods:

1. Write a try catch

2. Write one try and multiple catch es:

The second format is:

try{

Code that may cause problems

}Catch (exception class name 1 variable name 1){

Handling scheme for exception 1

}Catch (exception class name 2 variable name 2){

Handling scheme for exception 2

}... ...

 

Precautions when using the second scheme when handling multiple exceptions:

1. catch can only match the corresponding exception, and can only match one exception

2. It doesn't matter the abnormal order of the horizontal relationship, but if there is a parent-child inheritance relationship, the parent class must be placed last

3. If there is an error in the code in try, the code behind the error code in try will not be executed. It will match the exception in catch and execute the solution after matching. Try The code after catch executes normally.

4. The exception class name in catch should be as clear as possible and should not be handled with large exceptions

Code example:

public class Demo2 {
    public static void main(String[] args) {
        fun();
    }
    public static void fun(){
        int a=10;
        int b=0;
        int[] arr={1,2,3};
 
        try{
            System.out.println(a/b);
//            When executed here, an error is reported, and the code after this line in the catch is directly matched. The code after this line in the try is not executed
            System.out.println(arr[4]);
        }catch(ArithmeticException e){
            System.out.println("The divisor is 0 and cannot be divided");
        }catch(ArrayIndexOutOfBoundsException s){
            System.out.println("Subscript index out of bounds");
        }
        System.out.println("over");
    }
}

Output result:

  JDK1. How to handle multiple exceptions after 7:

try{

Possible problem codes

}catch(ArithmeticException | ArrayIndexOutOfBoundsException){

Solutions to problems

}

matters needing attention:

1. The processing method is consistent. Although this method is concise, it is not good enough. Only one solution is given for exceptions of multiple data types

2. In this way, catch can only write exception classes with horizontal relationship

give an example:

public class Demo3 {
    public static void main(String[] args) {
        fun();
    }
    public static void fun(){
        int a=10;
        int b=0;
        int[] arr={1,2,3};
 
        try{
            System.out.println(a/b);
            System.out.println(arr[4]);
        }catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
            System.out.println("If there is an error, report it wrong");
        }
        System.out.println("over");
    }
}

Output result:

 

Code example: compile time exception example:

use

Examples of date classes:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ExceptionDemo5 {
    public static void main(String[] args) {
        //Date conversion
        String s = "2022-02-16 15";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        try{
            Date date = sdf.parse(s);
            System.out.println(date);
        }catch (ParseException e){
            System.out.println("Date conversion exception");
        }
 
        System.out.println("over");
    }
}

Output result:

The difference between compile time exception and run-time exception:

Compile time exception: the processing that Java programs must display, otherwise the program will have errors and cannot be compiled and run

Run time exception: in general, try can be used just like compile time exception without handling and modifying code logic Catch processing

Methods in Throwable

getMessage() gets the exception information and returns a string.

toString() gets the exception class name and exception information, and returns a string.

printStackTrace() gets the exception class name and exception information, as well as the location of the exception in the program. The return value is void.

Code example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Demo4 {
    public static void main(String[] args) {
        String s = "2022-02-16 15";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        try {
            Date date = format.parse(s);
            System.out.println(date);
        } catch (ParseException p) {
            p.printStackTrace();
            String message = p.getMessage();
            System.out.println(message);//Unparseable date: "2022-02-16 15"
 
            String s1 = p.toString();
            System.out.println(s1);//java.text.ParseException: Unparseable date: "2022-02-16 15"
 
 
        }
        System.out.println("over");
    }
}

Output result: the red font is the output result of p.printStackTrace(), and the rest are the results of the other two methods in turn

 

finally

Finally: the body of the finally controlled statement will eventually be executed, except in special cases

Special case: the JVM exits before executing the body of the finally control statement

Format: try catch... finally

Code example:

public class Demo6 {
    public static void main(String[] args) {
        //Date conversion
        String s = "2022-02-16 16:";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        Date date = null;
 
        try {
            date = sdf.parse(s);
        }catch (ParseException e){
            e.printStackTrace();
        }finally {
            //In general, what is written in finally is for
            //IO operations and database operations are often encountered
            System.out.println("The code here will be executed!");
        }
 
        System.out.println(date);
    }
}

Output result:

If you let finally not execute, that is, to realize the special situation, you only need to add the stop code before finally executing

public class FinallyDemo1 {
    public static void main(String[] args) {
        //Date conversion
        String s = "2022-02-16 16:";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        Date date = null;
 
        try {
            date = sdf.parse(s);
        }catch (ParseException e){
            e.printStackTrace();
            System.exit(0); //Stop the program
        }finally {
            //In general, what is written in finally is for
            //IO operations and database operations are often encountered
            System.out.println("The code here will be executed!");
        }
 
        System.out.println(date);
    }
}

Output result:

Here, only the exception is output, and the content in finally is not executed.  

The difference between final,finally and finalize

Final: the final meaning can modify classes, member variables and member methods

Decorated class: class cannot be inherited

Decorated member variable: variable becomes constant

Decorated member method: method cannot be overridden

Finally: it is an exception handling try catch.. The finally part is generally used to release resources. Under normal circumstances, it will be executed unless the program stops before finally.

finalize: it is a method in the Object class. It is used for garbage collection. There is no stack reference to the space in the heap memory, but we are not sure when to recycle.

throws

When defining functional methods, the problems that arise need to be exposed for the caller to deal with. Java provides another solution for handling exceptions:

throws throw

Statement definition format:

throws exception class name

be careful:

1. This format must follow the method's curly braces and precede the curly braces

2. Try not to throw on the main method

Summary:

1. An exception is thrown during compilation, which must be handled by the caller in the future

2. The runtime exception is thrown, and the caller will still have to deal with it in the future

Code example: not processed

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Demo5 {
    public static void main(String[] args) throws ParseException {
        System.out.println("What a nice day today");
 
        fun();
 
        System.out.println("You can go for an outing");
 
    }
 
    public static void fun() throws ParseException {
        //Date conversion
        String s = "2022-02-16 15";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(s);
        System.out.println(date);
    }
}

Output result: here, the fun() method throws an exception to the caller's main method, the mian() method does not handle it, throws an exception to the JVM, and the JVM will not handle it, so the result is still an exception.

Code example: after throwing exception, the caller did the processing.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Demo5 {
    public static void main(String[] args) throws ParseException {
        System.out.println("What a nice day today");
        try {
            fun2();
        }catch (ArithmeticException e){
            e.printStackTrace();
        }
 
        System.out.println("You can go for an outing");
 
    }
 
    public static void fun2() throws ArithmeticException{
        int a = 10;
        int b = 0;
        System.out.println(a/b);
    }
}

Output result: an exception is reported, but after the caller main method is processed, the following code can be successfully executed.

 

throw 

When a situation occurs inside the function method that the program cannot continue to run and needs to jump, throw the exception object with throw.

Note: at this time, the object of the exception class is thrown with throw

Code example:

import java.text.ParseException;
 
public class ExceptionDemo8 {
    public static void main(String[] args) {
        try {
            fun();
        }catch (ArithmeticException e){
            e.printStackTrace();
        }catch (ParseException p){
            p.printStackTrace();
        }
 
        System.out.println("over");
    }
 
    public static void fun() throws ArithmeticException, ParseException {
        int a = 10;
        int b = 0;
 
        if(b==0){
            System.out.println("hello");
            throw new ArithmeticException();
        }else {
            System.out.println(a/b);
        }
    }
}

Output result:

The difference between throws and throw:

throws:

Used after the method declaration, followed by the exception class name

It can be separated from multiple exception class names by commas

Indicates that an exception is thrown and handled by the caller of the method

throws:

Indicates a possibility of exceptions that do not necessarily occur

throw is used in the method body, followed by the exception object name

Only one exception object name can be thrown

It means that an exception is thrown. If it is handled by the statement in the method body, throw will throw an exception. If it is executed, some exception must be thrown

If there is a return statement in catch, will the finally code still be executed? Will execute

If yes, before or after return. Execute between.

Code example:

public class ExceptionDemo9 {
    public static void main(String[] args) {
        System.out.println(getInt()); // 30
    }
 
    public static int getInt() {
        int a = 10;
        try {
            System.out.println(a / 0);
            a = 20;
        } catch (ArithmeticException e) {
            a = 30;
            return a; // At this point, a return path a=30 has been generated;
        } finally {
            a = 40;
            System.out.println(a);
        }
 
        return a;
    }
}

Output result:

Result interpretation: since a return path has been generated when the first return a is executed, if it is not finally, the value of 30 will be returned directly. However, since the content of finally will be executed anyway, the program is not completed at this time. It needs to be finally executed before it is completed. Therefore, 40 will be printed after executing finally, After execution, return to the main method and print the return value 30. The second return a will not be executed.  

If you put the second return a into finally, the result will become:

public class ExceptionDemo9 {
    public static void main(String[] args) {
        System.out.println(getInt()); // 30
    }
 
    public static int getInt() {
        int a = 10;
        try {
            System.out.println(a / 0);
            a = 20;
        } catch (ArithmeticException e) {
            a = 30;
            return a; // At this point, a return path a=30 has been generated;
        } finally {
            a = 40;
            System.out.println(a);
            return a;
        }
    }
}

 

Result interpretation: the steps before finally are the same as before. When finally is executed, print 40 first. In return a, a return path is generated at this time. Therefore, the last return path is returned here, so 40 is output again

Keywords: Java Back-end

Added by johanafm on Thu, 17 Feb 2022 04:00:01 +0200