↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Errors and Exception Handling in GoLang

Go handles errors through a simple pattern: functions can return an error as a second value, and that value should be checked before continuing. The page also shows that errors are used to represent unexpected cases, help keep code stable, and make programs easier to maintain.

Reading notes
#

  • Go functions return errors as a second value, and the error should be checked immediately before the next step.
  • The errors package provides New() for creating a basic error.
  • fmt.Errorf() creates a formatted error message.
  • An error is checked by comparing it with nil, since the zero value of an error is nil.
  • panic stops function execution when something unexpected happens.
  • recover can catch a panic inside a deferred function and allow execution to continue.
  • A custom error can be created by implementing the error interface with an Error() string method.
  • Go can return a value and an error together, then the error is checked after the call.
  • The blank identifier _ can be used to ignore the returned error.