Error Handling & Defer¶
Python's try/except mapped to Go's if err != nil pattern, and related error handling constructs.
try / except¶
raise¶
Multiple Exceptions¶
finally¶
Context Manager¶
Custom Exception¶
type NotFoundError struct {
Name string
}
// Implement the error interface
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s not found", e.Name)
}
func findUser(name string) error {
return &NotFoundError{Name: name}
}
// Use errors.As to extract the concrete error type
var nfe *NotFoundError
if errors.As(err, &nfe) {
fmt.Printf("Missing: %s\n", nfe.Name)
}
panic/recover is not normal error handling
Go has panic and recover, but they are reserved for truly unrecoverable errors
(e.g., programmer bugs). Normal error handling always uses return error.