<jupyter_start><jupyter_text>Handling errors``` {index} Handling errors```When an _error_ occurs in Python, an _exception_ is _raised_.  Error typesThe full list of built-in exceptions is available in the [documentation](https://docs.python.org/3/library/exceptions.htmlconcrete-exceptions).For example, when we create a tuple with only four elements and want to print the 5th element, we get this error message:    flower_names = ("iris",                    "poppy",                    "dandelion",                    "rose")    print(flower_names[4])    ---------------------------------------------------------------------------    IndexError                                Traceback (most recent call last)     in           4                 "rose")          5     ----> 6 print(flower_names[4])    IndexError: tuple index out of range    IndexError refers to incorrect index, such as out of bounds. Raising errorsIn-built functions trigger or _raise_ errors in Python. We can do that as well by using _raise_:    raise ValueError    ---------------------------------------------------------------------------    ValueError                                Traceback (most recent call last)     in     ----> 1 raise ValueError    ValueError:     Catching errors Try and except blocksTo handle errors in the code gracefully, we can use _try_ and _except_ blocks to avoid unnecessary crashes of the program. The _try_ block executes the program and if the program fails, exception is raised and we can recover from the error. The syntax is:    try:         some code    except ExceptionName1:         some code    except ExceptionName2:         some code    …    except:         lines to execute if there was an exception not caught above    else:         lines to execute if there was no exception at all_else_ is optional, at least one _except_ needs to be raised. An example code below:<jupyter_code>a = "ten"

try:
    
    # Try to create a number out of a string
    
    float(a)
    
except ValueError:
    
    # Raise an error if characters are not numbers
    
    print("Exception was raised.\nPlease use digits in your string.")<jupyter_output>Exception was raised.
Please use digits in your string.
{'fraction_non_alphanumeric': 0.11980108499095841, 'fraction_numerical': 0.0045207956600361665, 'mean_word_length': 1.9744623655913978, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 6, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '399632', 'license': 'MIT', 'n_tokens_mistral': 520, 'n_tokens_neox': 502, 'n_words': 250, 'path': 'coding/Intro to Python/Handling_errors.ipynb', 'repo_name': 'jrper/thebe-test', 'size': '2212'}