Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if an error occurred after opening a file.
Go
file, err := os.Open("test.txt") if [1] != nil { fmt.Println("Error opening file") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'file' instead of 'err' for errors.
Comparing 'err' to a value other than nil.
✗ Incorrect
The variable 'err' holds the error returned by os.Open. We check if 'err' is not nil to detect an error.
2fill in blank
mediumComplete the code to return an error from a function.
Go
func divide(a, b int) (int, error) {
if b == 0 {
return 0, [1].New("division by zero")
}
return a / b, nil
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fmt.New' instead of 'errors.New'.
Returning nil instead of an error when b is zero.
✗ Incorrect
The 'errors' package provides the New function to create a new error value.
3fill in blank
hardFix the error in the code to handle the error returned by strconv.Atoi.
Go
num, [1] := strconv.Atoi("123a") if err != nil { fmt.Println("Conversion error") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the error variable differently than 'err'.
Not checking the error after conversion.
✗ Incorrect
The error variable must be named 'err' to match the check in the if statement.
4fill in blank
hardFill both blanks to handle an error returned by ioutil.ReadFile.
Go
data, [1] := ioutil.ReadFile("file.txt") if [2] != nil { fmt.Println("Failed to read file") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for the error.
Checking the wrong variable for errors.
✗ Incorrect
The error variable is named 'err' and must be checked for nil to detect errors.
5fill in blank
hardFill all three blanks to create and check a custom error using fmt.Errorf.
Go
func checkAge(age int) error {
if age < 18 {
return [1].Errorf("age %d is too young", [2])
}
return [3]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'errors.New' without formatting.
Returning an error when age is valid.
✗ Incorrect
Use 'fmt.Errorf' to create a formatted error, pass 'age' as argument, and return nil if no error.