Junior — Middle
Are you familiar with exceptions in Go?
sobes.tech AI
Answer from AI
The Go language does not have traditional exceptions like Java or Python. Instead, Go uses return values for error handling — a function returns an error value that needs to be checked.
However, Go has a mechanism of panic and recover, which can be considered as an analog to exceptions, but it is intended for critical errors and should not be used for regular error handling.
Example of error handling in Go:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Using panic/recover:
func mayPanic() {
panic("something went wrong")
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
mayPanic()
fmt.Println("This code will not execute")
}