Java exception handling

Java exception handling

1. Abnormal handling: catch and throw model

Process One: Throwing

During the normal execution of the program, once an exception occurs, an object corresponding to the exception class is generated at the exception code, and the object is thrown.
Once the object is thrown, the program terminates.
Regarding the generation of exception objects: 1. The exception object automatically generated by the system; 2. Manually generate an exception object and throw (throw)

Process Two: Grab

That is, how to handle exceptions:

1.try-catch-finally

2.throws

2.try-catch-finally

try {
    // Statements where exceptions may occur
} catch(ExceptionType e) {
    // Handle exception statement
} finally {
    // clean code block
}
2.1 Description

1.finally is optional
2. Wrap the exception code through try, once a line appears, a corresponding exception class will be generated, and match it in the catch according to the type of the object;
3. Once the exception in the try matches a certain catch, it will enter the catch for exception handling, then jump out of the try-catch structure and continue to execute;
​ 4. If the exception type in the catch has no child-parent relationship, there is no order relationship;
​ 5. The exception in the catch has a sub-parent class relationship, and the sub-class declaration comes first;
6. Common exception object handling methods: String getMessage() and printStackTrace();
7. Variables declared in the try structure cannot be used after the try structure is released;
8. The try-catch-finally structure can be nested;

@Test
    public void test(){
        String str = "123";
        str = "abc";
        try {
            int num = Integer.parseInt(str);
        }catch (NullPointerException e){
            System.out.println("Null pointer exception occurs");
            //System.out.println(e.getMessage());
            //e.printStackTrace();
        } catch (NumberFormatException e){
            //System.out.println("Number conversion exception occurred");
            //System.out.println(e.getMessage());
            e.printStackTrace();
        }catch (Exception e){
            System.out.println("Abnormal");//Exception is the parent class

        }
    }

Use try-catch-finally to handle compile-time exceptions, so that the program will no longer report errors at compile time, but may report errors at runtime, which is equivalent to delaying compile-time exceptions until runtime to report errors

2.2Use of finally

1.finally is optional
​ 2. The statement in finally will be executed, even if there is an exception in the catch, there is a return statement, and there is no exception, etc., finally will be executed
​ 3. For resources such as database connections, input and output streams, and network programming sockets, the JVM cannot automatically recycle them. We need to manually release resources, so we need to declare them in finally, and the resources will be released regardless of whether there is an exception.

@Test
    public void testMethod(){
        int num = method();
        System.out.println(num);//Abnormal
                                // 2
    }

    public int method(){
        try {
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            return 2;
        }finally {
            System.out.println("Abnormal");
        }
    }

For file open read close operations:

@Test
    public void test2(){
        FileInputStream fis = null;
        try {
            File file = new File("hello.txt");
            fis = new FileInputStream(file);

            int data = fis.read();
            while(data != -1){
                System.out.print((char)data);
                data = fis.read();
            }

        } catch (IOException e) {
            e.printStackTrace();
//            throw new RuntimeException(e);
        }finally {
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

In development, because runtime exceptions are common, try-catch-finally is not used for runtime exceptions

3.throws + exception type

​ 1. Write in the declaration of the method to indicate possible exceptions. Once an exception occurs, an exception class object will be generated at the exception code. When this object meets the exception type, it will be thrown, and the code behind the exception will no longer implement.
2.throws just throws the exception to the caller, but does not resolve the exception, and the exception needs try-catch-finally processing.

@Test
    public static void main(String[] args){
        try{
            method2();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //throws + exception type
    public static void method2() throws IOException{
        method1();
    }

    public static void method1() throws FileNotFoundException, IOException{
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);

        int data = fis.read();
        while(data != -1){
            System.out.print((char)data);
            data = fis.read();
        }
        fis.close();

    }
4. How to choose two exception handling methods in development

​ If the overridden method in the parent class does not have a throws method to handle exceptions, the subclass cannot use throws either, and the subclass can only use try-catch-finally.

5. Custom exception class

1. Inherited from the existing exception structure, Exception and RuntimeException
2. Provide a global variable: serialVersionUID
3. Provide an overloaded constructor

//custom exception class
public class MyException extends Exception {
    static final long serialVersionUID = -7034897193246939L;
    public MyException(){}
    public MyException(String msg){
        super(msg);
    }
}

Tags: Java programming language

Posted by mrjam on Thu, 05 Jan 2023 15:42:30 +1030