11.7. Exception Define

11.7.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
    

11.7.2. Example

>>> class AstronautsOnlyError(Exception):
...     pass
>>>
>>>
>>> profession = 'pilot'
>>>
>>> if profession != 'astronaut':
...     raise AstronautsOnlyError
Traceback (most recent call last):
AstronautsOnlyError

11.7.3. Use Cases

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')

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

11.7.4. Assignments

Code 11.7. Solution
"""
* Assignment: Exception Custom Exception
* Required: no
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min

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

Polish:
    1. Zdefiniuj własny wyjątek `NegativeKelvinError`
    2. Sprawdź wartośc przekazaną do funckji jako `float`
    3. Jeżeli wartość jest mniejsza niż 0, podnieś `NegativeKelvinError`
    4. Wymagania niefunkcjonalne
        a. Rozwiązanie zapisz wewnątrz funkcji `result`
        b. Zwróć uwagę na poziom wcięć
    5. Uruchom doctesty - wszystkie muszą się powieść

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
"""


def result(value):
    ...