Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

try ... except ... finally Statement

try except else finally visualization

try Clause.

except Clause.

Exception matching

finally Clause.

[!CAUTION]

The return statement inside the finally takes precedence over the return statement inside the try clause!

def func():
    try:
        return 1
    finally:
        return 2
print(func()) # 2

[!TIP]

There are some objects with a defined standard clean-up actions after object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. E.g. with statement is one of them.

else Clause

raise

Exception Chaining

try:
    open("somefile.txt")
except OSError:
    raise RuntimeError("unable to handle error")

Dealing with Multiple Exceptions – ExceptionGroup

def f():
    excs = [OSError('error 1'), SystemError('error 2')]
    raise ExceptionGroup('there were problems', excs)
try:
    f()
except* OSError as e:
    print("There were OSErrors")
except* SystemError as e:
    print("There were SystemErrors")

Note how we discerned the exception inside a group with except*. Though this is a contrived example but I guess this can give you a glimpse of what it would look like in a more realistic code:

excs = []
for test in tests:
    try:
        test.run()
    except Exception as e:
        excs.append(e)
if excs:
   raise ExceptionGroup("Test Failures", excs)

Here for example we are running some tests and wanted to catch all the exceptions after we’ve executed all the tests and raise them all at once.

Why tests, and what are they? Testing in software engineering is the process where you automate testing your code by writing code :grinning:. This is gives us: - **Reproducibility**: you can simply rerun the offending test countless times to understand what is wrong. - **Automation**: No need to manually test your app with every change. - **Software quality**: It's much easier to write tests and then think of different cases.

YouTube/Aparat

Ref