[JavaSE Column 68] Exception capture and processing, try-catch-finally efficiently solve exception handling problems

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concepts and syntax of exception capture and handling in Java, and gives sample codes. Catching exceptions can handle error conditions that may occur during operation and prevent the program from terminating execution due to exceptions. By catching exceptions and taking appropriate measures, the program can be made more robust and stable.

insert image description here


1. Why do we need to catch exceptions

In Java, catching exceptions is a good programming practice, with the following 4 44 reasons, please study hard.

  1. Error handling : Catching exceptions can handle error conditions that may occur during operation and prevent the program from terminating execution due to exceptions. By catching exceptions and taking appropriate measures, the program can be made more robust and stable.
  2. Exception information : Catching exceptions can provide detailed information about exception occurrences, such as exception type, stack trace, etc., which is helpful for debugging and troubleshooting problems in the program. Abnormal information can be recorded for subsequent analysis and repair of problems.
  3. Fault tolerance : By catching exceptions, corresponding processing can be performed when an exception occurs to avoid program termination or unexpected results. Reasonable exception handling can make the program more fault-tolerant, handle abnormal situations gracefully, and improve the reliability and stability of the system.
  4. User-friendliness : catching exceptions can provide a more friendly user interface and error prompts. By catching exceptions and displaying error messages to users in an understandable way, you can improve user experience and help users better understand and solve problems.

All in all, catching exceptions is a good programming practice that can improve the robustness, reliability, and user-friendliness of the program. It enables the program to handle abnormal conditions that may occur during operation and take appropriate measures to handle exceptions. Ensure the normal execution of the program.

insert image description here


Two, try-catch statement

In Java, the ·try-catch· statement is used to catch and handle exceptions. Its basic syntax is as follows. Please copy it locally and try to execute it.

try {
    
    
    // 可能会引发异常的代码
} catch (ExceptionType1 e1) {
    
    
    // 处理 ExceptionType1 类型的异常
} catch (ExceptionType2 e2) {
    
    
    // 处理 ExceptionType2 类型的异常
} finally {
    
    
    // 可选部分,无论是否发生异常都会执行的代码
}

In trythe block, you can write code that may throw an exception. If an exception tryoccurs in the block, the program will jump to the corresponding catchblock and execute catchthe code in the block to handle the exception.

catchBlocks take an exception type as a parameter and are used to catch specific types of exceptions. Students can use multiple catchblocks to catch different types of exceptions for specific processing. catchThe code in the block will execute the appropriate logic based on the exception type.

finallyBlocks are optional and are used to write code that will be executed regardless of whether an exception occurs. finallyThe code in the block is usually used to release resources or perform cleanup operations.

try-catchThe statement blocks must be written in order, that is, the block is written first try, then catchthe block, and finally finallythe block. At the same time, part of catchblock and block can be omitted, but block is required.finallytry

The following is a sample code that demonstrates try-catchthe usage of the statement, please copy it locally and try to execute it.

try {
    
    
    int result = divide(10, 0);
    System.out.println("Result: " + result);
} catch (ArithmeticException e) {
    
    
    System.out.println("An arithmetic exception has occurred: " + e.getMessage());
} finally {
    
    
    System.out.println("Finally block is executed");
}

public static int divide(int num1, int num2) {
    
    
    return num1 / num2;
}

In the above code, we called divide(10, 0)the method, which does the division operation. Since the divisor is 0 00 ,ArithmeticExceptionan exception will be thrown.

Then, the exception is caught and processed by the catch block, and the exception information is output: An arithmetic exception has occurred: / by zero.

Regardless of whether an exception occurs, finallythe code in the block executes, outputting: Finally block is executed.

Use try-catchstatement blocks to catch and handle exceptions, avoid program termination, and improve program robustness and fault tolerance.

insert image description here


Three, try-finally statement

In Java, try-finallya statement is used to ensure that a certain piece of code will be executed regardless of whether an exception occurs. Its basic syntax is as follows, please study carefully.

try {
    
    
    // 可能会引发异常的代码
} finally {
    
    
    // 无论是否发生异常都会执行的代码
}

In trythe block, students can write code that may throw an exception.

The program executes finallythe code in the block whether or not an exception occurs. finallyBlocks are often used to release resources, close connections, or perform cleanup operations to ensure that necessary operations can be completed when the program ends.

If tryan exception occurs in the block, the program jumps to finallythe block before executing catchthe block (if any).

catchThe block handles the exception, and program execution continues with finallythe code in the block.

When finallythe execution of the block completes, the program continues executing the code following the exception handling.

Here is a sample code that demonstrates try-finallythe usage of the statement:

public class Example {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
    
    
            System.out.println("An arithmetic exception has occurred: " + e.getMessage());
        } finally {
    
    
            System.out.println("Finally block is executed");
        }
    }
    
    public static int divide(int num1, int num2) {
    
    
        try {
    
    
            return num1 / num2;
        } finally {
    
    
            System.out.println("Finally block inside divide() method is executed");
        }
    }
}

In the above code, we called divide(10, 0)the method, which does the division operation. Since the divisor is 0 00 ,ArithmeticExceptionan exception will be thrown. Then, the exception iscatchcaught and handled by the block, and the exception message is output:An arithmetic exception has occurred: / by zero.

Regardless of whether an exception occurs, finallythe code in the block executes, outputting: Finally block is executed.

At the same time, in divide()the method, regardless of whether an exception occurs, finallythe code in the block will also be executed, outputting: Finally block inside divide() method is executed.

Using try-finallya statement block can ensure that a certain piece of code will be executed in any case, regardless of whether an exception occurs, which is very useful for cleaning up resources and performing some necessary operations.

insert image description here


Four, try-catch-finally statement

In Java, try-catch-finallystatements are used to catch and handle exceptions, and at the same time ensure that a certain piece of code will be executed regardless of whether an exception occurs. Its basic syntax is as follows, please study carefully.

try {
    
    
    // 可能会引发异常的代码
} catch (ExceptionType1 e1) {
    
    
    // 处理ExceptionType1类型的异常
} catch (ExceptionType2 e2) {
    
    
    // 处理ExceptionType2类型的异常
} finally {
    
    
    // 无论是否发生异常都会执行的代码
}

In trya block, you can write code that might throw an exception. If tryan exception occurs in the block, the program will jump to the corresponding catchblock and execute catchthe code in the block to handle the exception. catchBlocks take an exception type as a parameter and are used to catch specific types of exceptions. You can use multiple catchblocks to catch different types of exceptions for specific handling.

catchThe code in the block will execute the appropriate logic based on the exception type. catchDifferent types of exceptions can be handled in each block, and catchmultiple exception types can be handled in one block, eg catch (ExceptionType1 | ExceptionType2 e).

finallyBlocks are optional and are used to write code that will be executed whether or not an exception occurs. finallyCode within a block is typically used to release resources or perform cleanup operations.

Note that try-catch-finallythe statement blocks must be written in order, that is, write trythe block first, then catchthe block, and finally finallythe block. At the same time, part of catchblock and block can be omitted, but block is required.finallytry

The following is a sample code that demonstrates try-catch-finallythe usage of the statement, please study carefully.

try {
    
    
    int result = divide(10, 0);
    System.out.println("Result: " + result);
} catch (ArithmeticException e) {
    
    
    System.out.println("An arithmetic exception has occurred: " + e.getMessage());
} finally {
    
    
    System.out.println("Finally block is executed");
}

public static int divide(int num1, int num2) {
    
    
    try {
    
    
        return num1 / num2;
    } finally {
    
    
        System.out.println("Finally block inside divide() method is executed");
    }
}

In the above code, we called divide(10, 0)the method, which does the division operation. Since the divisor is 0 00 ,ArithmeticExceptionan exception will be thrown.

Then, the exception is catchcaught and handled by the block, and the exception message is output: An arithmetic exception has occurred: / by zero.

Regardless of whether an exception occurs, finallythe code in the block executes, outputting: Finally block is executed.

At the same time, in divide()the method, regardless of whether an exception occurs, finallythe code in the block will also be executed, outputting: Finally block inside divide() method is executed.

Use try-catch-finallystatement blocks to catch and handle exceptions, while ensuring that a certain piece of code will be executed under all circumstances, regardless of whether an exception occurs or not. This is useful for cleaning up resources and performing some necessary operations.

insert image description here


5. Exception handling process

In Java, the process of exception handling has the following 7 7Step 7 , please study hard.

  1. An exception occurs : When an exception occurs during program execution, the JVM will throw an exception object.
  2. Exception capture : Use try-catch statement block to capture and handle exceptions. Write code that might throw an exception in a try block.
  3. Exception matching : When an exception occurs, the JVM will match the exception types in the catch block sequentially from top to bottom. If the corresponding exception type is matched, the program will jump to the matching catch block to execute the corresponding code.
  4. Exception handling : In the catch block, you can write logic to handle exceptions. This can include printing error messages, logging, rolling back transactions, and more. If no catch block matches the exception type, the exception will be passed up the call stack.
  5. Finally block execution : The code in the finally block will be executed regardless of whether an exception occurs or not. The finally block is usually used to release resources or perform cleanup operations.
  6. Exception propagation : If the exception is handled in the catch block, the program will continue to execute the code after the catch block. If the exception is not handled or a new exception is thrown after handling, the exception will be passed to the upper call stack until it is caught or causes the program to terminate execution.
  7. Exception chaining : In the catch block, new exceptions can be thrown through the throw keyword, passing the original exception as the cause of the new exception. This forms an exception chain, which better describes the process by which the exception occurred.

The purpose of exception handling is to improve the robustness and fault tolerance of the program and prevent the program from crashing due to exceptions. Reasonable use of exception handling can better
manage and handle error conditions and make the program more reliable.


6. Exception handling interview questions

  1. What are exceptions in Java? Give examples of common exception types.
  2. What does the try-catch-finally statement do? Please explain the order in which they are executed.
  3. What's the difference between throwsand throw?
  4. What is the difference between RuntimeException and Checked Exception? When should they be used?
  5. What is the exception handling chain? What does it do?
  6. In Java, can there be more than one catch statement in a catch block? If so, what is their order?
  7. What is the try-with-resources statement block? How does it differ from the traditional try-finally block?
  8. How to define custom exception class in Java? Why custom exception classes?
  9. What happens if you use a return statement inside a finally block?
  10. What are the best practices for exception handling? What suggestions do you have?

insert image description here


7. Summary

This article explains the concept and syntax of exception capture and processing in Java, and gives sample code. In the next blog, I will explain the usage of throw and throws keywords in Java.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132112145