Quick Answer
try-catch blocks with exception safety guarantees.
Understanding the Issue
C++ exceptions provide error handling without compromising RAII. Follow the strong exception safety guarantee for robust code.
The Problem
This code demonstrates the issue:
Cpp
Error
// Problem: Resource leak
void unsafe() {
int* ptr = new int[100];
throw runtime_error("Oops");
delete[] ptr; // Never reached
}
The Solution
Here's the corrected code:
Cpp
Fixed
// Solution: RAII approach
void safe() {
vector<int> v(100); // Self-cleaning
throw runtime_error("No problem");
}
Key Takeaways
Use RAII types to ensure exception safety.