`try-catch-finally` and `try-with-resource` in Java

try-catch-finallyand in Javatry-with-resource

〇、Other related blogs

Detailed explanation of Java exception

https://blog.csdn.net/qq_29689343/article/details/95736854

1. Try-catch-finally captures and handles exceptions

1 Overview

Introduction

try-catch-finallyIt is the most basic exception handling mechanism. It consists of three keywords: try, catchand finally. The code block is placed tryin the block. If an exception is thrown during the execution of the block, it will jump to catchthe block for exception handling. finallyThe code in the block is always executed, whether or not an exception occurs.

tryA block may be followed by zero, one or more catchblocks, catchor must be followed by a block if there are no blocks finally.

finallyExecution mechanism

Whether or not the exception is caught, finallythe block will always be executed!

There is a possibility that it will not be executed:

  1. If the System.exit() method appears in the try or catch block, the JVM will immediately terminate the program, resulting in the finally block not being executed.
  2. If an internal error or system crash occurs in the JVM before the finally block is executed, the finally block will not be executed.
  3. If the thread the program is running on is forcibly terminated (such as using the Thread.stop() method), then the finally block may not be executed.
  4. If an infinite loop occurs inside a try or catch block, the finally block will never be executed.

2. Code format

try {
    
    
    // 可能抛出异常的代码
    // ...
} catch (ExceptionType1 e1) {
    
    
    // 处理 ExceptionType1 异常
    // ...
} catch (ExceptionType2 e2) {
    
    
    // 处理 ExceptionType2 异常
    // ...
} finally {
    
    
    // 在任何情况下都会执行的代码
    // ...
}

3. Best practice

  1. Enclose code that might throw an exception in a try block. Put code that might throw an exception in a try block so that exceptions can be caught and handled.
  2. Catch and handle exceptions in a catch block. In the catch block, you can specify the type of exception to handle, and provide an exception handler. This ensures that the program does not crash when an exception occurs, but continues execution .
  3. Don't ignore exceptions . When handling exceptions, do not throw the exception into the method caller, but instead use the appropriate exception handler to handle the exception. This makes the code more robust and reliable.
  4. Use multiple catch blocks . If your code may throw multiple types of exceptions, you can use multiple catch blocks to catch and handle each type of exception. This gives you more control over the exception handling process and ensures that your code handles each type of exception correctly.
  5. Release resources in finally block . In the finally block, you can specify code to be executed after the code has finished executing. This is typically used to free resources , such as closing files or network connections, etc. The code in the finally block will be executed regardless of whether the code throws an exception or not.
  6. Use local variables whenever possible . Using local variables in try blocks reduces the scope of exceptions , making the code easier to understand and maintain.
  7. Avoid throwing exceptions . If an exception is thrown in a finally block, it may cause the code to become more complicated and difficult to understand. Therefore, you should avoid throwing exceptions in the finally block and instead use a suitable exception handler to handle exceptions.
  8. Use returnstatements with care : Be careful when using statements in tryblocks, catchblocks, and blocks to make sure the logic is correct and as expected. A statement within a block may override a block or statements within a block .finallyreturnfinallyreturntrycatchreturn

Two, try-with-resources automatically closes resources

1 Overview

try-with-resourcesIt is an exception handling mechanism introduced from Java 7. It is used to automatically close resources that implement java.lang.AutoCloseablethe interface or java.io.Closeable, such as files or network connections, to ensure that they are closed properly, even in the event of an exception.

When using try-with-resources, we can trydeclare one or more resources in the statement , and these resources will be automatically closed after the end of the code block. The declaration and initialization of resources are separated by semicolons.

2. Code example

try (ResourceType1 resource1 = new ResourceType1(); ResourceType2 resource2 = new ResourceType2()) {
    
    
    // 使用 resource1 和 resource2 的代码
    // ...
} catch (ExceptionType e) {
    
    
    // 处理异常
    // ...
}

In the above example, ResourceType1and are resource typesResourceType2 that implement AutoCloseablethe interface . They are declared and initialized within a block, and are automatically closed after the code block ends. If an exception occurs, the program will jump to the corresponding block for exception handling, and before that , the resource will be closed automatically .trycatch

3. Three code blocks of try catch finally in try-with-resources

In a statement, blocks, blocks, and blocks try-with-resourcescan be included , and their meanings and functions are the same as traditional blocks. **They are explained in detail below:trycatchfinallytry-catch-finally

  1. tryBlocks: tryBlocks contain code that requires exception handling. In trya block, we can declare and initialize one or more resource objects, which must implement AutoCloseablethe interface or its subinterfaces Closeable. tryAfter the code in the block is executed, these resources will be automatically closed regardless of whether an exception occurs.
  2. catchBlock: catchBlocks are used to catch and handle tryexceptions thrown in the block. It can contain one or more catchclauses, each for handling a specific type of exception. When tryan exception occurs in the code in the block, the program will jump to the matching catchblock and execute the corresponding exception handling code.
  3. finallyBlock: finallyThe code in the block trywill be executed after the code in the block is executed, regardless of whether an exception occurs. It is usually used to perform some necessary finishing operations, such as releasing resources, cleaning up temporary data, etc. The code within the block is executed even if the statement is used within trythe block or within the block.catchreturnfinally

code example

try (ResourceType resource = new ResourceType()) {
    
    
    // 可能抛出异常的代码
    // ...
} catch (ExceptionType e) {
    
    
    // 处理特定类型的异常
    // ...
} finally {
    
    
    // 在任何情况下都会执行的代码
    // ...
}

Can only tryblock!

4. Close resources

In try-with-resources, the resource is properly closed whether or not an exception occurs. Even if tryan exception occurs in the block, the closing operation of the resource is performed.

When try-with-resourcesthe statement finishes executing, close()the method of each resource object is automatically called to close the resource. This is achieved through bytecode generated by the compiler, ensuring proper closing of resources.

If tryan exception occurs within a block, control flow immediately jumps to catchthe block or terminates the program, but before the jump, the compiler calls close()methods on each resource object to ensure they are properly closed.

This is an important advantage try-with-resourcesover traditional try-catch-finallyblocks, which ensures automatic closing of resources regardless of exceptions. This avoids resource leaks and simplifies the code for resource management.

5. Best practices

  1. Use try-with-resourcesto manage resources: For resources that need to be closed manually, such as files, database connections, etc., try to use try-with-resourcesto automatically manage the closing of resources. This ensures that resources are properly closed after use and avoids resource leaks.
  2. Implements AutoCloseablethe interface: To be used try-with-resources, the resource class must implement AutoCloseablethe interface or its subinterfaces Closeable. These two interfaces define close()methods for releasing resources. Make sure the resource class implements these interfaces correctly.
  3. Declare and initialize only necessary resources: In try-with-resourcesthe statement, only declare and initialize the resources that need to be used. Avoid declaring unnecessary resources to keep your code clean and concise.
  4. Handling of multiple resources : tryMultiple resources can be declared and initialized in the statement, and they will be closed in order of declaration. The declaration and initialization of each resource are separated by a semicolon.
  5. The order of resources : For resources with dependencies, they should be declared and initialized in the correct order to ensure that the dependent resources can be properly closed after use.
  6. Exception handling: If trythe code in the block throws an exception, try-with-resourcesthe declared resource is automatically closed, and then the last exception is thrown. You can use catcha block to catch and handle the exception, or pass the exception on to the upper caller.
  7. Nested try-with-resources: A statement can try-with-resourcesbe nested within another statement try-with-resources. Make sure inner resources are declared before outer resources to ensure proper shutdown order.
  8. Use the right resource type: Choose the right resource type, depending on the nature and needs of the resource. The Java standard library provides many AutoCloseableresource classes that implement interfaces, such as FileInputStream, , Socketand so on. You can also customize AutoCloseablethe resource class that implements the interface.

Guess you like

Origin blog.csdn.net/qq_29689343/article/details/131343221