15.6. Exception Define

15.6.1. Define Custom Exceptions

  • Class which inherits from Exception

  • Exceptions should have Error at the end of their names

>>> class MyError(Exception):
...     pass
>>>
>>>
>>> raise MyError
Traceback (most recent call last):
MyError
>>>
>>> raise MyError('More verbose description')
Traceback (most recent call last):
MyError: More verbose description

15.6.2. Example

>>> class InsufficientPrivileges(Exception):
...     pass
>>>
>>>
>>> role = 'user'
>>>
>>> if role != 'admin':
...     raise InsufficientPrivileges
Traceback (most recent call last):
InsufficientPrivileges

15.6.3. Use Case - 0x01

Django Framework Use-case of Custom Exceptions:

>>> 
... from django.contrib.auth.models import User
>>>
>>>
>>> def login(request):
...     username = request.POST.get('username')
...     password = request.POST.get('password')
...
...     try:
...         user = User.objects.get(username, password)
...     except User.DoesNotExist:
...         print('Sorry, no such user in database')

15.6.4. Use Case - 0x02

  • Dragon

>>> class Dragon:
...     def take_damage(self, damage):
...         raise self.IsDead
...
...     class IsDead(Exception):
...         pass
>>>
>>>
>>> wawelski = Dragon()
>>>
>>> try:
...     wawelski.take_damage(10)
... except Dragon.IsDead:
...     print('Dragon is dead')
Dragon is dead

15.6.5. Assignments

Code 15.7. Solution
"""
* Assignment: Exception Custom Exception
* Type: homework
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Define custom exception `NegativeKelvinError`
    2. Check value `value` passed to a `result` function
    3. If `value` is lower than 0, raise `NegativeKelvinError`
    4. Write solution inside `result` function
    5. Run doctests - all must succeed

Polish:
    1. Zdefiniuj własny wyjątek `NegativeKelvinError`
    2. Sprawdź wartość `value` przekazaną do funckji `result`
    3. Jeżeli `value` jest mniejsze niż 0, podnieś `NegativeKelvinError`
    4. Rozwiązanie zapisz wewnątrz funkcji `result`
    5. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `class`
    * `pass`
    * `raise`
    * `if`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass

    >>> isclass(NegativeKelvinError)
    True
    >>> issubclass(NegativeKelvinError, Exception)
    True
    >>> result(1)
    >>> result(0)
    >>> result(-1)
    Traceback (most recent call last):
    exception_custom_a.NegativeKelvinError
"""

# Define custom exception `NegativeKelvinError`
# Check value `value` passed to a `result` function
# If `value` is lower than 0, raise `NegativeKelvinError`
# Write solution inside `result` function
# type: Callable[[int], None]
def result(value):
    ...


Code 15.8. Solution
"""
* Assignment: Exception Custom Exception
* Type: homework
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Define custom exception `IsDead`
    2. Check value `health` passed to a `hero` function
    3. If `health` is equal or lower than 0, raise `IsDead`
    4. Write solution inside `hero` function
    5. Run doctests - all must succeed

Polish:
    1. Zdefiniuj własny wyjątek `IsDead`
    2. Sprawdź wartość `health` przekazaną do funckji `hero`
    3. Jeżeli `health` jest mniejsza lub równa 0, podnieś `IsDead`
    4. Rozwiązanie zapisz wewnątrz funkcji `result`
    5. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `class`
    * `pass`
    * `raise`
    * `if`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass

    >>> isclass(IsDead)
    True
    >>> issubclass(IsDead, Exception)
    True
    >>> hero(1)
    >>> hero(0)
    Traceback (most recent call last):
    exception_custom_b.IsDead
    >>> hero(-1)
    Traceback (most recent call last):
    exception_custom_b.IsDead
"""

# Define custom exception `IsDead`
# Check value `health` passed to a `hero` function
# If `health` is equal or lower than 0, raise `IsDead`
# Write solution inside `hero` function
# type: Callable[[int], None]
def hero(health):
    ...