Learning Go by Jon Bodner

Learning Go by Jon Bodner

Author:Jon Bodner [Jon Bodner]
Language: eng
Format: epub, pdf
Publisher: O'Reilly Media, Inc.
Published: 2021-03-07T16:00:00+00:00


panic and recover

In previous chapters, we’ve mentioned panics in passing without going into any details on what they are. Go generates a panic whenever there is a situation where the Go runtime is unable to figure out what should happen next. This could be due to a programming error (like an attempt to read past the end of a slice) or environmental problem (like running out of memory). As soon as a panic happens, the current function exits immediately and any defers attached to the current function start running. When those defers complete, the defers attached to the calling function run, and so on, until main is reached. The program then exits with a message and a stack trace.

If there are situations in your programs that unrecoverable, you can create your own panics. The built-in function panic takes one parameter, which can be of any type. Usually, it is a string. Let’s make a trivial program that panics and run it on The Go Playground at https://play.golang.org/p/_bkJBEA1FLs :



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.