0
0
Goprogramming~10 mins

Handling errors in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aos
Bfile
Cnil
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'file' instead of 'err' for errors.
Comparing 'err' to a value other than nil.
2fill in blank
medium

Complete 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'
Amath
Berrors
Cfmt
Dos
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fmt.New' instead of 'errors.New'.
Returning nil instead of an error when b is zero.
3fill in blank
hard

Fix 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'
Aerr
Berror
Cnum
DconvErr
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the error variable differently than 'err'.
Not checking the error after conversion.
4fill in blank
hard

Fill 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'
Aerr
Bdata
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for the error.
Checking the wrong variable for errors.
5fill in blank
hard

Fill 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'
Afmt
Bage
Cnil
Derrors
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'errors.New' without formatting.
Returning an error when age is valid.