try:
fh = open(path)
print(fh.read())
except:
print('No such file '+path)
finally:
fh.close()
Using try…except blocks for predictable operations (such as file opening) creates unnecessary overhead.
When an exception is thrown, the exception object itself consumes CPU cycles and RAM for its creation and destruction.
For simple, testable conditions (e.g., checking if a file exists), logical checks (like os.path.isfile) are more efficient and avoid the performance cost of exception handling.
This rule currently focuses on the "file open" use case, but the principle applies to other predictable scenarios (e.g., loops, data constructions).
try:
fh = open(path)
print(fh.read())
except:
print('No such file '+path)
finally:
fh.close()
if os.path.isfile(path):
fh = open(path, 'r')
print(fh.read())
fh.close