2023-09-24
When I first started using Go, it took me some time to become familiar with its error handling approach. In comparison to the traditional control flow approach, where exceptions are handled in a separate block (try/catch), modern languages like Go and Rust use a different approach called explicit error handling. In this approach, the error is one of the return values, and the developer is expected to check and handle it right away.
For example, in Go:
value, err := someFunction()
if err != nil {
// handle the error
}
In Rust, you would use Result<T, E>
, which is an enum with two variants: Ok(value)
and Err(value)
:
match some_function() {
Ok(value) => {
// use the value
},
Err(e) => {
// handle the error
},
}
Both languages also have a similar concept called "panic" mode, which represents unrecoverable errors that should interrupt the execution.
Explicit error handling arguably helps developers write more readable error handling code because it is closely related to the actual place where the error will occur, as opposed to the control flow approach, where the catch
block might be in a separate function or buried deep within many other function calls that might produce the error, or even worse, hidden by a generic exception.