Complete the code to check if an error occurred after opening a file.
file, err := os.Open("test.txt") if [1] != nil { fmt.Println("Error opening file") }
In Go, errors are returned as the second value. We check if err is not nil to detect an error.
Complete the code to handle an error returned by a function.
result, [1] := divide(10, 0) if err != nil { fmt.Println("Cannot divide by zero") }
The error variable is commonly named err in Go to follow conventions and clarity.
Fix the error in the code that ignores error handling.
file, _ := os.Open("data.txt") [1] := file.Stat() fmt.Println(info.Size())
To handle errors properly, assign both the returned info and error from file.Stat(). This allows checking the error before using info.
Fill both blanks to correctly handle an error when reading a file.
data, [1] := os.ReadFile("config.json") if [2] != nil { fmt.Println("Failed to read file") }
Use the variable err to capture and check the error returned by os.ReadFile.
Fill all three blanks to handle an error and print the file size.
file, [1] := os.Open("log.txt") if [2] != nil { fmt.Println("Error opening file") return } info, [3] := file.Stat()
Use err consistently to capture and check errors from both os.Open and file.Stat().