Summary:
When we do certain operations that need cleanup, we can "schedule" the cleanup operations which would be run when the function returns no matter which path that happens, including due to panic.
Detailed answer:
- Programming languages strive to provide constructs that facilitate simpler and less error-prone development. (E.g. why should Golang support garbage collection when we can free the memory ourselves)
- A function can return at multiple points. The user might overlook doing certain cleanup operations in some paths
- Some cleanup operations are not relevant in all return paths
- Also, it is better to keep the cleanup code closer to the original operation which needed the cleanup
- When we do certain operations that need cleanup, we can "schedule" the cleanup operations which would be run when the function returns no matter which path that happens.