Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.✗ Incorrect
The errors.New function creates a new error with the given message, which can be returned.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning
string instead of error.Not declaring the error return type.
✗ Incorrect
The function returns an int and an error type to indicate success or failure.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the file handle
f instead of the error.Returning
nil when there is an error.✗ Incorrect
When os.Open returns an error, it should be returned directly as err.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a plain string without formatting.
Not passing the age variable to format the message.
✗ Incorrect
fmt.Errorf formats the error message with the age value.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the wrong variable for error.
Printing the error in the else block.
✗ Incorrect
Check if err is not nil to handle errors, otherwise print the result.