C++ says "We have try at home."
4 months ago
- #programming-languages
- #C++
- #exception-handling
- Many languages with exceptions support a 'finally' clause for executing code after a block, regardless of exceptions.
- C++ lacks a 'finally' clause but uses destructors to execute cleanup code when leaving a scope.
- Behavior varies when both the guarded block and 'finally' or destructor throw exceptions: Java, Python, JavaScript, and C# overwrite the original exception, while C++ terminates the program.
- Python 3.2+ saves the original exception as context when a new exception is raised in 'finally'.
- C++ destructors must not throw exceptions if the destructor is running due to an exception, or the program terminates.
- Microsoft's WIL library provides 'scope_exit' for C++ cleanup but terminates if the cleanup lambda throws.
- Function-try-blocks in C++ can handle exceptions in constructors but have limitations in cleanup.
- Python's exception chaining in 'finally' was added in Python 3.2, preserving the original exception.
- Java's 'getSuppressed' method handles exceptions in try-with-resources but not in 'finally'.
- Best practices in C++ include using RAII and avoiding exceptions in destructors.