What happens if an exception occurs inside a catch block?
try {}
catch(...)
{
stream.close(); // IO exception here
}
What's the default behaviour?
CodePudding user response:
Nothing special will happen. A new exception object will be initialized by the throw
expression inside the call and a search for a matching catch
handler will start, which on escaping the function call will continue on the nearest enclosing try
block (enclosing the shown try
/catch
pair). The old exception object will be destroyed during stack unwinding when leaving the old handler, since it wasn't rethrown.
CodePudding user response:
If you encounter an exception in the catch block, then that exception will be thrown.
If you don't want to throw the exception, you can add one more catch block for this exception.
try {
}catch(...){
try{
stream.close(); // IO exception here
}catch(IOException ioException){
}
}
CodePudding user response:
To the best of my recollection:
#include <cstdio>
#include <fstream>
#include <stdexcept>
static auto foo(char const* path) try {
if (not path)
throw std::runtime_error("path was nullptr");
else
std::printf("Opening file '%s'\n", path);
auto f = std::ifstream(path);
if (not f)
throw std::runtime_error("Failed to open file in foo(char const*)");
char x[5] {};
f.read(x, 4); // 4 chars '\0'
std::printf("File type: %s\n", x 1);
return x[1]; // 'E' on linux
} catch (std::runtime_error const& e) {
// If an exception occurs here, unless the call to foo(char const*)
// was itself in a try-catch, the exception will be uncaught and std::terminate will be called
// Whether std::terminate causes any stack unwinding to occur is implementation defined.
// (That's not great.)
// If the function was marked `noexcept (true)` then std::terminate would get immediately called.
// f is destructed at the end of the scope (before the catch).
// This is called "RAII": https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
std::fprintf(stderr, "%s: An exception occured:\n\t'%s'\n", __func__, e.what());
throw; // rethrows the caught exception
}
int main(int, char** argv) {
std::printf("%c", foo(argv[0]));
}
In a function try-catch
block: the file object gets destructed when it goes out of scope; Regardless of the exception state.