<jupyter_start><jupyter_text>Error handling- hide: false- toc: false- comments: true- categories: [python]<jupyter_code>%config InlineBackend.figure_format = 'retina'
%load_ext autoreload
%autoreload 2<jupyter_output><empty_output><jupyter_text>A brief reminder of different ways to handle errors in Python. Print message only<jupyter_code>def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        print(e)
        
divide(4, 0)<jupyter_output>division by zero<jupyter_text>Raise original error (traceback and message)<jupyter_code>def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        raise e
        
divide(4, 0)<jupyter_output><empty_output><jupyter_text>Raise different error type to be clearer that invalid value was supplied<jupyter_code>def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        raise ValueError('invalid inputs; division by zero is undefined')
        
divide(4, 0)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08699902248289346, 'fraction_numerical': 0.006842619745845552, 'mean_word_length': 3.970873786407767, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '105888', 'license': 'Apache-2.0', 'n_tokens_mistral': 343, 'n_tokens_neox': 334, 'n_words': 94, 'path': 'backups/.ipynb_checkpoints/2021-01-15-error-handling-checkpoint.ipynb', 'repo_name': 'fabiangunzinger/blog', 'size': '1023'}