try-catch-finally in Go is used for exception handling. The syntax is: try: contains the code that needs to handle exceptions. If an exception occurs, it will immediately go to catch or finally. catch: Handle the exception thrown in try. If there is no exception, it will not be executed. finally: Will be executed regardless of whether there is an exception, often used to clean up resources.
In the Go language, the try-catch-finally
statement is used Handle exceptions. Here is the syntax:
func try() { defer recover() // 可选,用于捕获恐慌异常 ... // 你的需要处理异常的代码 }
try
The block contains the code that needs to handle the exception. If an exception occurs, the statements in the try
block will immediately stop execution and execution flow will go to the catch
block or the finally
block. The
catch
block is used to handle exceptions thrown in the try
block. If the code in the try
block does not throw an exception, the catch
block will not be executed.
catch
The syntax of the block is:
func catch() { r := recover() // 捕获 `try` 块中的恐慌异常 ... // 处理异常的代码 }
##finally block regardless of
try block whether It will be executed if an exception is thrown. It is typically used to clean up resources or perform other finishing operations.
finally The syntax of the block is:
func finally() { ... // 清理资源或执行其他收尾操作 }
import ( "fmt" "io/ioutil" ) func readFile(filename string) { defer recover() contents, err := ioutil.ReadFile(filename) if err != nil { panic(err) } fmt.Println(string(contents)) } func main() { readFile("existing_file.txt") readFile("non_existing_file.txt") }
try block contains the code to read the file
existing_file.txt. If the file exists and can be read successfully, the
try block will execute normally and the contents will be printed to the console. The
catch block is used to handle errors that may occur in the
try block. If the file does not exist or cannot be read, the
try block will throw an exception and execution will go to the
catch block. In the
catch block, the exception is caught and printed to the console. The
finally block is optional, but it can be used to perform cleanup operations such as closing a file handle.
The above is the detailed content of try-catch-finally in Golang exception handling. For more information, please follow other related articles on the PHP Chinese website!