0
0
Goprogramming~10 mins

Why error handling is required in Go - Test Your Understanding

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'
Afile
Berr
Cnil
Dos
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the wrong variable for error
Not checking for nil before using the file
2fill in blank
medium

Complete the code to handle an error returned by a function.

Go
result, [1] := divide(10, 0)
if err != nil {
    fmt.Println("Cannot divide by zero")
}
Drag options to blanks, or click blank then click option'
Afail
Berror
Ce
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name other than 'err' for errors
Ignoring the error variable
3fill in blank
hard

Fix the error in the code that ignores error handling.

Go
file, _ := os.Open("data.txt")
[1] := file.Stat()
fmt.Println(info.Size())
Drag options to blanks, or click blank then click option'
Ainfo, err
BfileInfo
Cinfo
DfileInfo, err
Attempts:
3 left
💡 Hint
Common Mistakes
Ignoring the error returned by Stat
Using undefined variable 'info' without assignment
4fill in blank
hard

Fill both blanks to correctly handle an error when reading a file.

Go
data, [1] := os.ReadFile("config.json")
if [2] != nil {
    fmt.Println("Failed to read file")
}
Drag options to blanks, or click blank then click option'
Aerr
Berror
Cfail
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for error capture and check
Not checking the error at all
5fill in blank
hard

Fill all three blanks to handle an error and print the file size.

Go
file, [1] := os.Open("log.txt")
if [2] != nil {
    fmt.Println("Error opening file")
    return
}
info, [3] := file.Stat()
Drag options to blanks, or click blank then click option'
Aerr
Berror
Cerr2
Dfail
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for errors
Not checking errors before using file info