[Java] Catch Exception in Exception Handling

In Java, any statement that may throw an exception can be try ... catchcaught. Put the statements that may cause exceptions try { ... }in the middle, and then use catch to capture the corresponding Exceptionand its subclasses.

Multiple catch statements

Multiple catchstatements can be used, each catchcapturing the corresponding Exceptionclass and its subclasses. JVMAfter the exception is caught, catchthe statement will be matched from top to bottom. catchAfter a certain match is found, catchthe code block will be executed, and then the match will not continue.

Simply put: catchonly one of multiple statements can be executed. For example:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (IOException e) {
    
    
        System.out.println(e);
    } catch (NumberFormatException e) {
    
    
        System.out.println(e);
    }
}

When there are more catchthan one, catchthe order is very important: the subclass must be written first. For example:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (IOException e) {
    
    
        System.out.println("IO error");
    } catch (UnsupportedEncodingException e) {
    
     // 永远捕获不到
        System.out.println("Bad encoding");
    }
}

For the above code, UnsupportedEncodingExceptionthe exception is never caught because it is IOExceptiona subclass of . When an exception is thrown UnsupportedEncodingException, it will be catch (IOException e) { ... }caught and executed.

Therefore, the correct way to write is to put the subclass in front:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (UnsupportedEncodingException e) {
    
    
        System.out.println("Bad encoding");
    } catch (IOException e) {
    
    
        System.out.println("IO error");
    }
}

finallyStatement
Regardless of whether an exception occurs, if we want to execute some statements, such as cleanup, how to write?

You can write the execution statement several times: put the ones that are executed normally try, and catchwrite each one again. For example:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
        System.out.println("END");
    } catch (UnsupportedEncodingException e) {
    
    
        System.out.println("Bad encoding");
        System.out.println("END");
    } catch (IOException e) {
    
    
        System.out.println("IO error");
        System.out.println("END");
    }
}

System.out.println("END");The above code will execute this statement regardless of whether an exception occurs .

So how to eliminate these duplicate codes? Java的try ... catchThe mechanism also provides finallystatements, finallyblocks of statements that are guaranteed to be executed with or without errors. The above code can be rewritten as follows:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (UnsupportedEncodingException e) {
    
    
        System.out.println("Bad encoding");
    } catch (IOException e) {
    
    
        System.out.println("IO error");
    } finally {
    
    
        System.out.println("END");
    }
}

Note that finallythere are several features:

finallyStatements are not required and can be written or not;
finallythey are always executed last.
If no exception occurs, the statement block is executed normally try { ... }, and then executed finally. If an exception occurs, interrupt the execution of try { ... }the statement block, then jump to execute the matching catch statement block, and finally execute it finally.

It can be seen that finallyit is used to ensure that some code must be executed.

In some cases, there can be none catch, just use try ... finallythe structure. For example:

void process(String file) throws IOException {
    
    
    try {
    
    
        ...
    } finally {
    
    
        System.out.println("END");
    }
}

Because the method declares the exceptions that may be thrown, it is not necessary to write catch.

Catching multiple exceptions
If the processing logic of some exceptions is the same, but the exception itself does not have an inheritance relationship, then you have to write multiple catch clauses:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (IOException e) {
    
    
        System.out.println("Bad input");
    } catch (NumberFormatException e) {
    
    
        System.out.println("Bad input");
    } catch (Exception e) {
    
    
        System.out.println("Unknown error");
    }
}

Since the code to handle IOExceptionthe NumberFormatExceptionsum is the same, we can combine the two uses | together:

public static void main(String[] args) {
    
    
    try {
    
    
        process1();
        process2();
        process3();
    } catch (IOException | NumberFormatException e) {
    
     // IOException或NumberFormatException
        System.out.println("Bad input");
    } catch (Exception e) {
    
    
        System.out.println("Unknown error");
    }
}

summary

When using try ... catch ... finally:

The matching order of multiple catchstatements is very important, and subclasses must be placed first;

finallyThe statement guarantees that it will be executed with or without exception, it is optional;

A catchstatement can also match multiple non-inheritance exceptions.

Guess you like

Origin blog.csdn.net/ihero/article/details/132160389