Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Preamble One of the concepts used in writing Python code is \"Easier to ask for

ID: 654245 • Letter: P

Question

Preamble
One of the concepts used in writing Python code is "Easier to ask for forgiveness than permission", aka EAFP. Literally this means that instead of doing checks, whether an operation is possible, you do the operation and "ask forgiveness" if what you do fails. Technically this means (just an example with no particular meaning):

try:
    obj.x = 10
    obj.y = 20
except AttributeError:
    pass
This technique is oftenly used when the code in try..except block is known to run without any errors in most cases, or if the code is rearly executed. The same code with preliminary checks would look as follows:

if hasattr(obj, 'x'):
    obj.x = 10

if hasattr(obj, 'y'):
    obj.y = 20
C++ practices
While generally not an issue in Python, C++ has a "heritage" flame war of "function returning error status" vs. "throwing exceptions". This has been discussed a lot, but I can't find any good source of information which describes whether the Pyhton-like EAFP is applicable in Python.

E.g. consider the following:

if (node.has_element('x')) {
    node['x'] = 10;
}
versus

try {
    node['x'] = 10;
}
catch(ElementNotFoundException e) {
    // pass
}
Which approach is generally used in C++ code? If performance is not the issue, would you write EAFP-fashioned code? Thank you.

Explanation / Answer

It's hard to classify something as being generally used in C++. Not only do many companies have their own conventions, but C++ by design lets you compile without exception support at all (no support for stack unwinding, function prologue/epilogue).

That said; ignored exceptions are considered an anti-pattern in most C++ applications, and should usually be complemented by a good, documented reason. The reason not only being performance, but because it's considered an abuse of the try/catch mechanism. The idiom is that it should only be used for exceptional cases, not the normal flow of a program (unlike in Python, in which it is even used for

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote