4 ms·
For some context here's another error handler in Google Go: defer func() { if r := recover(); r != nil { if err, ok := r.(runtime.Error
by 0xABADC0DA 15y ago
For some context here's another error handler in Google Go:
defer func() {
if r := recover(); r != nil {
if err, ok := r.(runtime.Error); ok {
if err.String() == "runtime error: index out of range" {
// handle bad index
return
}
}
panic(r)
}
}()
vs
try {
}
catch (IndexOutOfBoundsException ex) {
// handle bad index
}
A language where you have to resort to string compare to handle invalid array accesses can't be use as a model for good error handling IMO.
Of course that's just the tip of an iceberg with no way for IDEs/tools to know what return is an error, no way to know at a glance if "_" was an ignored error or ignored other extra return value, plus other fundamental problems caused by implicit types.
- enneff 15y agoWhose crazy code is that? NOT idiomatic. If you need to recover from bad slice indexes then your code is broken and you have way more to worry about than a messy recover closure.
- 0xABADC0DA 15y ago> If you need to recover from bad slice indexes then your [error handler] code is broken You bring up a good point that when resorting to value comparisons for error handling instead of type comparisons it's easy to make mistakes. The code is as far as I can tell a simplest way to handle an index out of bounds, but to also handle a 'slice out of bounds' it would need to also compare to the string value "runtime error: slice bounds out of range" -- not helping the case for error handling in Google Go. This code strikingly shows deficiencies in Google Go non-local error handling: - Tons of boilerplate (defer, recover, re-panic, type check, value check) - Not scoped so can only handle an error once per function - Have to do value tests in addition since types are very generic due to implicit interfaces - Error values are poorly defined - Result for higher-level caller is buried deep in the function and non-obvious These problems extend to all non-local error handling in Google Go, not just for this specific case of array and string indexes. That the idiomatic way to 'handle' an error is to abort the program is another separate problem.