Imagine you are writing a program that reads a file. Sometimes the file might not exist or be unreadable. Why is it important to handle such errors in Go?
Think about what happens if the program tries to read a missing file without checking for errors.
Error handling lets the program know when something goes wrong. This way, it can fix the problem, warn the user, or stop safely instead of crashing or giving wrong results.
Look at this Go code that tries to open a file. What will it print if the file does not exist?
package main import ( "fmt" "os" ) func main() { file, err := os.Open("nofile.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() fmt.Println("File opened successfully") }
What does the program do when err is not nil?
The program checks if there is an error opening the file. If the file does not exist, err is not nil, so it prints the error message and stops.
This Go code tries to read a file but has a mistake in error handling. What is the problem?
package main import ( "fmt" "os" ) func main() { file, err := os.Open("data.txt") if err == nil { fmt.Println("Error opening file") return } defer file.Close() fmt.Println("File opened successfully") }
Remember, err is nil when there is no error.
The code wrongly treats err == nil as an error case. It should check if err != nil to detect errors.
Which of these Go code snippets will cause a compile-time error?
Check the syntax rules for if-else statements and defer usage.
Option D misses braces for the else block with defer, causing a syntax error.
Consider this Go function that divides two numbers and returns an error if dividing by zero. What is the value of 'result' after calling divide(10, 0)?
package main import ( "errors" "fmt" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("cannot divide by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) result = -1 } fmt.Println("Result:", result) }
What happens when divide returns an error? How is 'result' changed?
The function returns an error and 0 when dividing by zero. The main function detects the error and sets result to -1 before printing.