Skip to content

Latest commit

 

History

History
48 lines (40 loc) · 2.56 KB

use_with_try_doctest.rst

File metadata and controls

48 lines (40 loc) · 2.56 KB

Use with the try-except block

You can use easycheck functions within a try-except block to catch exceptions. See:

>>> from easycheck import check_if_not, check_type
>>> def foo(a, b):
...    try:
...        check_type(a, int, message='a must be integer')
...        check_type(b, int, message='b must be integer')
...        check_if_not(a > b, ValueError, 'a must not be higher than b')
...    except Exception as e:
...        print(f'Error: {e}')
>>> foo('string', 10)
Error: a must be integer
>>> foo(10, 'string')
Error: b must be integer
>>> foo(11, 10)
Error: a must not be higher than b
>>> foo(9, 10)

You can get similar functionality using the function that catches exceptions, that is, catch_check() (see how to catch exceptions instead of raise them). In order to do so, you could do the following:

>>> from easycheck import check_if_not, check_type, catch_check
>>> def bar(a, b):
...    a_check = catch_check(check_type, a, int, message='a must be integer')
...    b_check = catch_check(check_type, b, int, message='b must be integer')
...    if not a_check and not b_check:
...        a_b_check = catch_check(check_if_not, a > b, ValueError, 'a must not be higher than b')
...        if a_b_check:
...            print(f'Error: {a_b_check}')
...    else:
...        print(f'Error: {a_check}, {b_check}')
>>> bar('string', 10)
Error: a must be integer, None
>>> bar(10, 'string')
Error: None, b must be integer
>>> bar(11, 10)
Error: a must not be higher than b
>>> foo(9, 10)

Note that this code is much more complex than the above code that uses the try-except block. This is because we need to take care of not running catch_check(check_if_not, a > b, ValueError, 'a must not be higher than b') if a > b gives an error (as does the comparison of an integer with a string). Using the catch_exception() function, we need to catch each such a check, something that the try-except block did before for all the checks. What's more, we did not format what print() returns, since it would introduce additional complexity.

As we see, in many instances the simpler approach with the try-except block will be better and more readable than using the catch_exception() function.