Hello! Today's expedition is about understanding Go's error messages. We'll examine how these error messages work, their structure, and the most common types that we're likely to encounter. Let's get started!
Go handles errors in a way that's somewhat different from other languages. Here, an error is a predefined interface, which isn't meant to signal an exception but to be a standard return type. When your Go code encounters a situation it doesn’t know how to handle, the typical response is to return an error to signal this to the caller of the function.
Go's error messages comprise the following:
Description: This string describes what went wrong.
To illustrate, let's consider this code error:
The code:
The error:
Although the error message provides not much of insight, it's sufficiently direct for us to understand that there's a missing parenthesis.
For this error:
Descriptionissyntax error: unexpected newline in argument list; possibly missing comma or )
Every error contains a description to help you understand what's not right.
Syntax errors occur when the code violates Go's language rules, preventing the compiler from parsing and thus compiling the code. These errors are usually caught at compile time. Examples include:
-
Missing Brackets: Forgetting to close a bracket or parenthesis can lead to a syntax error.
This raises:
-
Misplaced Keywords: Using a keyword in the wrong context can also cause syntax errors.
This would typically raise:
Logical errors happen when the code does not perform as intended or produces unexpected results. These errors are not caught at compile time because the code is syntactically correct. Some examples include:
- Incorrect Loop Condition: This can cause the program to behave unexpectedly or run for an extremely long time.
Although it compiles, the loop will run for a very long time because i decreases instead of increases. While not technically infinite (it would eventually overflow after going through all negative integers), it would run for so long that it appears infinite in practical terms.
- Wrong Variable Used: Using a different variable than intended can cause logical errors.
This prints the total instead of the average.
