c++exceptionerror-handlingtry-catch

does catch block share the scope of the try block?


Surprisingly, I can't find an answer to that by googling and searching SO (there are lots of similar questions on SO but related to other languages).

I suspect that the answer is no. If so, there is an obvious inconvenience, e.g.

try
{
  std::string fname = constructFileName(); // can throw MyException
  ofstream f;
  f.exceptions(ofstream::failbit | ofstream::badbit);
  f.open(fname.c_str());
  // ...
}
catch (ofstream::failure &e)
{
  cout << "opening file " << fname << " failed\n"; // fname is not in the scope
}
catch (MyException &e)
{
  cout << "constructing file name failed\n";
}

If my assumption is correct, how do you deal with this? By moving the std::string fname; out of try, I guess?

I understand that a scope is defined by a {} block, but this seems as a reasonable case for, hmm, exception. Is the reason for that that objects can be not fully constructed if an exception is thrown?


Solution

  • Does catch block share the scope of the try block?

    No.

    How do you deal with this? By moving the std::string fname; out of try, I guess?

    Yes.

    I understand that a scope is defined by a {} block, but this seems as a reasonable case for, hmm, exception. Is the reason for that that objects can be not fully constructed if an exception is thrown?

    The last thing C++ needs is more complex rules and exceptions to rules. :-)