Execution errors such as attempting to index an array out of bounds trigger a run-time panic equivalent to a call of the built-in function
panic
with a value of the implementation-defined interface typeruntime.Error
. That type satisfies the predeclared interface type error. The exact error values that represent distinct run-time error conditions are unspecified.package runtime type Error interface { error // and perhaps other methods }
We’ve already covered the built-in panic
function, and the related recover
. This section of the spec is specifically about panics created by the runtime (as oppose to simply “at runtime”–which are all panics).
The most useful thing to take away from this section is that panics created by the Go runtime will be of the specific type runtime.Error
. If we look at the documentation for that type, we see:
type Error interface { error // RuntimeError is a no-op function but // serves to distinguish types that are run time // errors from ordinary errors: a type is a // run time error if it has a RuntimeError method. RuntimeError() }
The Error interface identifies a run time error.
So this gives us a handy little way to tell in our own programs, whether a panic we’ve recovered from comes from the Go runtime, or some other code.
func doSomething() {
defer func() {
if r := recover(); r != nil {
_, isRuntime := r.(runtime.Error)
fmt.Printf("Recovered! Runtime error? %t\n", isRuntime)
}
}()
// some code that may panic
}
Well, almost.
There’s nothing preventing you from adding a RuntimeError()
to your own arbitrary error types, if you so choose. Just, please, don’t do that.
type notARuntimeErrorLOL string
func (e notARuntimeErrorLOL) Error() string {
return string(e)
}
// RuntimeError causes [notARuntimeErrorLOL] to implement the [runtime.Error]
// interface for laughts.
func (notARuntimeErrorLOL) RuntimeError() {}
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)