gpt4 book ai didi

java - Java 的 'defer' 是什么

转载 作者:IT王子 更新时间:2023-10-29 01:13:48 26 4
gpt4 key购买 nike

这只是 Go 代码的一个简短示例:

package main

import "fmt"

func main() {
defer fmt.Println("world") //use of keyword 'defer'

fmt.Println("hello")
}

我在 Java 中找到了“延迟”的等价物。

我可以使用'defer'来代替

try {
//do something
} finally {
//code using defer
}

有没有不使用 try/catch/finally 的替代方案?

最佳答案

Java 7 有一个 try-with-resources statement .

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

关于java - Java 的 'defer' 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com