16.5. Exception Except

  • try - block of code that may raise exception

  • finally - block of code that is executed always (even if there was exception)

  • try is required and then one of the others blocks

16.5.1. Finally

  • finally is executed always (even if there was exception)

finally is executed always (even if there was exception). Typically it is used to close file, connection or transaction to database:

>>> def login(username, password):
...     raise PermissionError('Cannot login')
>>>
>>>
>>> try:
...     login('alice', 'secret')
... except PermissionError:
...     print('Permission error')
... finally:
...     print('Disconnect')
...
Permission error
Disconnect

16.5.2. Assignments

# %% About
# - Name: Exception Catch Finally
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Modify function `convert`
# 2. Try converting argument `value` to `float`
# 3. If any exception occurs, then return `False`
# 4. If no exception occurs, then return `True`
# 5. After all (doesn't matter if exception occurred or not), print 'done'
# 6. Use `try`, `except`, `else`, `finally`
# 7. Do not leave empty `except`
# 8. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `convert`
# 2. Spróbuj przekonwertować argument `value` do `float`
# 3. Jeżeli wystąpi jakikolwiek wyjątek, to zwróć `False`
# 4. Jeżeli nie wystąpi żaden wyjątek, to zwróć `True`
# 5. Po wszystkim (niezależnie czy wystąpił wyjątek czy nie), wypisz 'done'
# 6. Użyj `try`, `except`, `else`, `finally`
# 7. Nie pozostawiaj pustego `except`
# 8. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `try`
# - `except`
# - `else`
# - `finally`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> result = open(__file__).read()
>>> assert 'except'+':' not in result, \
'Do not leave empty except'

>>> convert(1)
done
True
>>> convert(1.0)
done
True
>>> convert(1,0)
Traceback (most recent call last):
TypeError: convert() takes 1 positional argument but 2 were given

>>> convert('1')
done
True
>>> convert('1.0')
done
True
>>> convert('1,0')
done
False

>>> convert((1.0))
done
True
>>> convert((1.0))
done
True
>>> convert((1,0))
done
False

>>> convert([1])
done
False
>>> convert([1.0])
done
False
>>> convert([1,0])
done
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable, Any
convert: Callable[[Any], bool]

# %% Data

# %% Result
def convert(value):
    try:
        float(value)
    except Exception:
        return False
    else:
        return True