try-catch-finally
and in Javatry-with-resource
Article directory
〇、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-finally
It is the most basic exception handling mechanism. It consists of three keywords: try
, catch
and finally
. The code block is placed try
in the block. If an exception is thrown during the execution of the block, it will jump to catch
the block for exception handling. finally
The code in the block is always executed, whether or not an exception occurs.
try
A block may be followed by zero, one or more catch
blocks, catch
or must be followed by a block if there are no blocks finally
.
finally
Execution mechanism
Whether or not the exception is caught, finally
the block will always be executed!
There is a possibility that it will not be executed:
- 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.
- If an internal error or system crash occurs in the JVM before the finally block is executed, the finally block will not be executed.
- 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.
- 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
- 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.
- 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 .
- 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.
- 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.
- 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.
- Use local variables whenever possible . Using local variables in try blocks reduces the scope of exceptions , making the code easier to understand and maintain.
- 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.
- Use
return
statements with care : Be careful when using statements intry
blocks,catch
blocks, 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 .finally
return
finally
return
try
catch
return
Two, try-with-resources automatically closes resources
1 Overview
try-with-resources
It is an exception handling mechanism introduced from Java 7. It is used to automatically close resources that implement java.lang.AutoCloseable
the 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 try
declare 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, ResourceType1
and are resource typesResourceType2
that implement AutoCloseable
the 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 .try
catch
3. Three code blocks of try catch finally in try-with-resources
In a statement, blocks, blocks, and blocks try-with-resources
can be included , and their meanings and functions are the same as traditional blocks. **They are explained in detail below:try
catch
finally
try-catch-finally
try
Blocks:try
Blocks contain code that requires exception handling. Intry
a block, we can declare and initialize one or more resource objects, which must implementAutoCloseable
the interface or its subinterfacesCloseable
.try
After the code in the block is executed, these resources will be automatically closed regardless of whether an exception occurs.catch
Block:catch
Blocks are used to catch and handletry
exceptions thrown in the block. It can contain one or morecatch
clauses, each for handling a specific type of exception. Whentry
an exception occurs in the code in the block, the program will jump to the matchingcatch
block and execute the corresponding exception handling code.finally
Block:finally
The code in the blocktry
will 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 withintry
the block or within the block.catch
return
finally
code example
try (ResourceType resource = new ResourceType()) {
// 可能抛出异常的代码
// ...
} catch (ExceptionType e) {
// 处理特定类型的异常
// ...
} finally {
// 在任何情况下都会执行的代码
// ...
}
Can only try
block!
4. Close resources
In try-with-resources
, the resource is properly closed whether or not an exception occurs. Even if try
an exception occurs in the block, the closing operation of the resource is performed.
When try-with-resources
the 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 try
an exception occurs within a block, control flow immediately jumps to catch
the 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-resources
over traditional try-catch-finally
blocks, which ensures automatic closing of resources regardless of exceptions. This avoids resource leaks and simplifies the code for resource management.
5. Best practices
- Use
try-with-resources
to manage resources: For resources that need to be closed manually, such as files, database connections, etc., try to usetry-with-resources
to automatically manage the closing of resources. This ensures that resources are properly closed after use and avoids resource leaks. - Implements
AutoCloseable
the interface: To be usedtry-with-resources
, the resource class must implementAutoCloseable
the interface or its subinterfacesCloseable
. These two interfaces defineclose()
methods for releasing resources. Make sure the resource class implements these interfaces correctly. - Declare and initialize only necessary resources: In
try-with-resources
the statement, only declare and initialize the resources that need to be used. Avoid declaring unnecessary resources to keep your code clean and concise. - Handling of multiple resources :
try
Multiple 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. - 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.
- Exception handling: If
try
the code in the block throws an exception,try-with-resources
the declared resource is automatically closed, and then the last exception is thrown. You can usecatch
a block to catch and handle the exception, or pass the exception on to the upper caller. - Nested
try-with-resources
: A statement cantry-with-resources
be nested within another statementtry-with-resources
. Make sure inner resources are declared before outer resources to ensure proper shutdown order. - 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
AutoCloseable
resource classes that implement interfaces, such asFileInputStream
, ,Socket
and so on. You can also customizeAutoCloseable
the resource class that implements the interface.