There are three ways to handle custom function exceptions in Go: use the panic built-in function (see the article for syntax). Practical case: define divide function, when the divisor is 0, panic advantages: convenient, customizable error message, can be Disadvantages of handling errors at different function levels: disrupting program flow, making debugging difficult
Handling custom functions in Go There are many methods for exceptions. One way is to use the panic
built-in function. panic
passes program control to the recover
function, allowing you to handle the exception and safely resume program execution.
package main import "fmt" func main() { f := func() { panic("custom error") } defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() f() }
Note: The defer
statement must be placed before the panic
statement so that panic occurs
is called when.
We define a custom function named divide
, which divides two numbers. If the divisor is 0, the function triggers an exception:
package main import "fmt" func main() { divide := func(numerator, denominator int) float64 { if denominator == 0 { // 触发错误 panic("不能除以 0") } return float64(numerator) / float64(denominator) } defer func() { if r := recover(); r != nil { fmt.Println("错误:", r) } }() result := divide(10, 2) fmt.Println(result) // 输出:5 result = divide(10, 0) // 触发错误 }
Output:
5 错误: 不能除以 0
The above is the detailed content of Exception handling in golang custom function implementation. For more information, please follow other related articles on the PHP Chinese website!