Golang does not have the exception handling structure of try… Catch… But uses defer, panic and recover to handle exceptions.
1. Defer, which literally means delay and postponement, is to delay the method behind defer until the method wrapping the method returns for execution.
From the above code, we can see that defer has the following features:
1) Defer pushes the method onto the stack and finally executes
2) When there are multiple defers, the principle of last in first out is followed
3) Defer is the state delay when running the sequence to the method. The effect can be seen from the change of I value
4) The stack pressing and out of stack of defer have performance loss. Avoid writing defer inside the for loop
2. Panic, a fatal error that the system cannot handle.
When the program reports an error, we can see that the panic logo will appear on the prompt. Of course, we can also use the panic function, but when we use it, the code behind it will not run.
3. Recover () is used to catch exceptions, which is equivalent to catch, but recover must be in the defer method to take effect.