0
0
Goprogramming~10 mins

Returning 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 return an error from the function.

Go
func check(value int) error {
    if value < 0 {
        return [1]("negative value")
    }
    return nil
}
Drag options to blanks, or click blank then click option'
Aerrors.New
Bpanic
Clog.Fatal
Dfmt.Println
Attempts:
3 left
💡 Hint
Common Mistakes
Using fmt.Println instead of returning an error.
Using panic which stops the program instead of returning an error.
2fill in blank
medium

Complete the code to declare the function returns an error.

Go
func divide(a, b int) (int, [1]) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
Drag options to blanks, or click blank then click option'
Abool
Bint
Cerror
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Returning string instead of error.
Not declaring the error return type.
3fill in blank
hard

Fix the error in the code to properly return an error.

Go
func openFile(name string) error {
    f, err := os.Open(name)
    if err != nil {
        return [1]
    }
    defer f.Close()
    return nil
}
Drag options to blanks, or click blank then click option'
Aerr
Bf
Cnil
Dos.Open
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the file handle f instead of the error.
Returning nil when there is an error.
4fill in blank
hard

Fill both blanks to create and return a formatted error message.

Go
func validate(age int) error {
    if age < 18 {
        return fmt.Errorf([1], [2])
    }
    return nil
}
Drag options to blanks, or click blank then click option'
A"age %d is too young"
Bage
C"error"
Dfmt.Errorf
Attempts:
3 left
💡 Hint
Common Mistakes
Using a plain string without formatting.
Not passing the age variable to format the message.
5fill in blank
hard

Fill all three blanks to check error and handle it properly.

Go
result, err := divide(10, 0)
if [1] != nil {
    fmt.Println([2])
} else {
    fmt.Println([3])
}
Drag options to blanks, or click blank then click option'
Aerr
Cresult
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the wrong variable for error.
Printing the error in the else block.