Junior — Middle
Kas teate, mis on erandid (Exception) Go keeles?
sobes.tech AI
Vastus AI-lt
In the Go language, there are no traditional exceptions like in Java or Python. Instead, Go uses return values for error handling: the function returns an error value (error), which must be checked.
However, Go has a mechanism of panic and recover, which can be considered analogous to exceptions, but it is intended for critical errors and should not be used for normal 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 after panic:", r)
}
}()
mayPanic()
fmt.Println("This code will not execute")
}