For that matter, how is the called method supposed to determine what the state of the world even is? And why on Earth would we trust it to do so? Is encapsulation not even a thing anymore? I really just don’t understand.
- Accessing array out of bounds: panic
- File not found: error
When you access an array out of bounds, the Go runtime initiates the panic. On the other hand, for a condition that the program should hold but doesn't, the program author should initiate the panic. For example, in the exhaustive switch below, reaching the default case means that either you have somehow incorrectly allowed the construction of an invalid token value earlier in your program, or you have missed to account for a valid token value in this function.
func (t token) symbol() byte {
switch token {
case add: return '+'
case sub: return '-'
case mul: return '*'
case quo: return '/'
default: panic("unknown token")
}
}
Errors are different.For example, url.Parse returns an error if its input string is an invalidly-formatted URL.
package url
func Parse(rawURL string) (*URL, error)put another way: how is the non-exhaustiveness of the switch statement qualitatively different from an out-of-bounds array access? they both are equivalent package author mistakes.
the java runtime raises IndexOutOfBounds exceptions for bad array accesses, but do each function call or your program with an IndexOutOfBounds exception handler?