In Go, we can handle errors using defer
and panic
statements.
defer
statement: This statement is used to define a function that will be called at the end of the surrounding function, irrespective of whether it returns normally or panics. We can use defer
to handle errors in the following way:func someFunction() {
defer func() {
if err := recover(); err != nil {
// Handle the error here
fmt.Println("Recovered from panic:", err)
}
}()
// Code that might panic
panic("Something went wrong!")
}
In the code above, we defer a function which checks if there has been a panic and handles it accordingly.
panic
statement: This statement is used to abruptly terminate the current function and start panicking. We can use panic
to throw errors in the following way:func someFunction() {
if condition {
panic("An error occurred!")
}
}
In the code above, if the condition is true, the function will panic and the error message will be displayed.
By combining defer
and panic
, we can implement error handling in Go. When a panic occurs, it triggers the deferred function which can capture and handle the error appropriately.