I was reading Google C++ Style Guide, and got confused in the Exceptions part. One of the cons of using it, according to the guide is:
Exception safety requires both RAII
and different coding practices. Lots
of supporting machinery is needed to
make writing correct exception-safe
code easy. Further, to avoid requiring
readers to understand the entire call
graph, exception-safe code must
isolate logic that writes to
persistent state into a “commit”
phase. This will have both benefits
and costs (perhaps where you’re forced
to obfuscate code to isolate the
commit). Allowing exceptions would
force us to always pay those costs
even when they’re not worth
Specifically, the statement that I didn’t understand is this:
(…) exception-safe code must isolate
logic that writes to persistent state
into a “commit” phase.
and this:
(…) perhaps where you’re forced to
obfuscate code to isolate the commit (…).
I think I’m not used to the terms “persistent state”, “commit phase”, “obfuscate code to isolate the commit”. It’d be nice some small explanations, examples or references about these terms and possibly why this is true.
“writes to persistent state” mean roughly “writes to a file” or “writes to a database“.
“into a ‘commit’ phase.” means roughly “Doing all the writing at once”
“perhaps where you’re forced to obfuscate code to isolate the commit” means roughly “This may make the code hard to read” (Slight misuse of the word “obfuscate” which means to deliberately make something hard to read, while here they mean inadvertantly make it hard to read, but that misuse may have been intentional, for dramatic effect)
Elaborating more: “writes to persistent state” more closely means “Write out, to some permanent media, all the details about this object that would be needed to recreate it”. If writing was interrupted by an exception, then those “written out details” (i.e. “persistent state”) could contain half the new state and half the old state, leading to an invalid object when it was recreated. Hence writing the state must be done as one uninterruptable act.