Free GoLang Error Handling Questions and Answers — Questions and Answers
Question 1: Which package is used to create and handle errors in Go?
- os
- errors (Correct answer)
- fmt
- log
Correct answer: errors
The `errors` package in Go provides fundamental interfaces and functions for error handling. Specifically, `errors.New` is used to create a simple error message. While `fmt` can format error messages and `log` can output them, `errors` is the dedicated package for defining and working with error types.
Question 2: What is the idiomatic way to handle errors in Go?
- Use try-catch blocks.
- Check if the returned error is nil. (Correct answer)
- Ignore errors if they are not critical.
- Panic on every error.
Correct answer: Check if the returned error is nil.
Go's idiomatic error handling involves functions returning an `error` as their last return value. Callers then check if this returned error is `nil`; a `nil` error indicates success, while a non-`nil` error indicates that something went wrong. This explicit check promotes robust error handling without relying on exceptions or try-catch blocks.
Question 3: Which of the following methods can be used to create a custom error in Go?
- errors.New("custom error") (Correct answer)
- fmt.Errorf("custom error: %v", value) (Correct answer)
- panic("custom error")
- Implementing the Error() method for a custom type. (Correct answer)
Correct answer: errors.New("custom error")
In Go, you can create custom errors in several ways. `errors.New("custom error")` creates a simple error with a static message. `fmt.Errorf("custom error: %v", value)` creates a formatted error, often including dynamic information. Implementing the `Error() string` method for a custom struct type allows for more complex, typed errors.
Question 4: When should panic be used instead of returning an error in Go?
- For minor errors that can be ignored.
- When an unexpected and unrecoverable condition occurs. (Correct answer)
- To simplify error handling in a function.
- To debug your code.
Correct answer: When an unexpected and unrecoverable condition occurs.
`panic` in Go should be reserved for truly exceptional and unrecoverable situations, such as programming errors or critical system failures that prevent the program from continuing safely. For most anticipated errors, returning an `error` value is the idiomatic and preferred approach, allowing the caller to handle or recover gracefully. Using `panic` for minor errors would lead to program crashes.
Which package is used to create and handle errors in Go?