Recover from a Panic
How to catch a panic error when it’s thrown? That’s what this post hopes to answer.
Go has a built in
recover() function which allows you to pick up and run some code when a panic is thrown. This can be useful for regaining execution of your program, or allowing the panic to happen, but to clean up state (like files) before your program closes.
If you are curious what the structure of a panic is, see it’s docs here.
We use defer to run a function after main has completed. In our example we have it in main, but you can catch a panic within a specific function by using the same idea. We then use recover to get the panic, and in our example print it to screen.