Junior — Middle
In what case and why is the throw operator used without passing an exception in a catch block?
sobes.tech AI
Answer from AI
The throw; operator without arguments in a catch block is used to re-throw the currently caught exception. This is useful when you want to handle an exception partially (for example, log it or perform some cleanup), and then pass it further up the call stack for more global handling.
Example:
try {
// code that may throw an exception
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl; // log
throw; // re-throw the same exception
}
Important: throw; without parameters can only be used inside a catch block. Using throw without parameters outside of catch will result in a compilation error.