.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/basics/exceptions.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_basics_exceptions.py: ================== 1.18 Exceptions ================== This lesson shows the usage of exceptions in python .. GENERATED FROM PYTHON SOURCE LINES 9-11 An exception is basically an error which is raised when a statement or command fails in python. .. GENERATED FROM PYTHON SOURCE LINES 11-16 .. code-block:: default a = 2 assert isinstance(a, int) .. GENERATED FROM PYTHON SOURCE LINES 17-20 The function ``isinstance`` is being used here to check the ``type`` of a python object. The above statement did not return anything because the assertion was successful. However if the assertion fails, we get a special kind of error called ``AssertionError``. .. GENERATED FROM PYTHON SOURCE LINES 23-27 AssertionError --------------- If we run the code given below, it will result in ``AssertionError`` because the variable `a` is ``int`` type and not ``float`` type. .. GENERATED FROM PYTHON SOURCE LINES 27-31 .. code-block:: default # uncomment following 1 line # assert isinstance(a, float) .. GENERATED FROM PYTHON SOURCE LINES 32-33 We can write more useful error messages instead of throwing just ``AssertionError`` as follows, .. GENERATED FROM PYTHON SOURCE LINES 33-37 .. code-block:: default # uncomment following 1 line # assert isinstance(a, float), f"a is not float but is of {type(float)} type" .. GENERATED FROM PYTHON SOURCE LINES 38-39 Similar to ``AssertionError``, there are many other types of errors/exceptions in python .. GENERATED FROM PYTHON SOURCE LINES 41-44 TypeError ----------- This error is raised when an operation is failed due to wrong ``type`` of a variable. .. GENERATED FROM PYTHON SOURCE LINES 44-48 .. code-block:: default # uncomment following line # 4 + 'a' # -> TypeError: unsupported operand type(s) for +: 'int' and 'str' .. GENERATED FROM PYTHON SOURCE LINES 49-50 Since we can not add a string into an integer, we got ``TypeError`` above. .. GENERATED FROM PYTHON SOURCE LINES 52-55 ModuleNotFoundError --------------------- This error is raised when a specific module that we are importing is not **available/installed**. .. GENERATED FROM PYTHON SOURCE LINES 57-61 .. code-block:: default # uncomment following 1 line # import ai4water # -> ModuleNotFoundError: No module named 'ai4water' .. GENERATED FROM PYTHON SOURCE LINES 62-71 Since ``ai4water`` package is not installed, we got ``ModuleNotFoundError`` above. Whenever we import a variable, function or class or any python object, python searches in all the directories (folders) which are in its ``path``. So when we say a package is not installed or available, it means, this package or the object that we are importing is not available in any of the directories in the ``path``. In other words we also say that, this package/object is not available in python's path. If we want to check what are the lists of directories/folders in python's path, we can do this by printing the value of ``sys.path``. .. GENERATED FROM PYTHON SOURCE LINES 73-74 sys.path returns a ``list`` so we can iterate over it. .. GENERATED FROM PYTHON SOURCE LINES 74-80 .. code-block:: default import sys for p in sys.path: print(p) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/latest/docs/source /home/docs/.asdf/installs/python/3.9.19/lib/python39.zip /home/docs/.asdf/installs/python/3.9.19/lib/python3.9 /home/docs/.asdf/installs/python/3.9.19/lib/python3.9/lib-dynload /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/envs/latest/lib/python3.9/site-packages /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/latest/scripts/basics .. GENERATED FROM PYTHON SOURCE LINES 81-84 KeyError ----------- This error is raised when a specific key is not available in a dictionary. .. GENERATED FROM PYTHON SOURCE LINES 84-90 .. code-block:: default human = {"name": "Ali"} # uncomment following 1 line # print(human['age']) # KeyError: 'age' .. GENERATED FROM PYTHON SOURCE LINES 91-93 Since the dictionary `human` does not have `age` key, we will get ``KeyError``, if we will run the above cell. .. GENERATED FROM PYTHON SOURCE LINES 95-99 PermissionError ---------------- This error is raised when the user does not have permission to access the file or to do an operation on such a file for which he/she does not have corresponding rights. .. GENERATED FROM PYTHON SOURCE LINES 99-108 .. code-block:: default f = open('NewFile.txt', 'w') import os # uncomment the following line # os.remove('NewFile.txt') # -> PermissionError .. GENERATED FROM PYTHON SOURCE LINES 109-111 since the file `NewFile.txt` was already opened, we can not delete it and got ``PermissionError``. .. GENERATED FROM PYTHON SOURCE LINES 111-115 .. code-block:: default f.close() os.remove('NewFile.txt') .. GENERATED FROM PYTHON SOURCE LINES 116-117 Once we close the file using ``f.close()``, then we can delete the file. .. GENERATED FROM PYTHON SOURCE LINES 119-121 ``PermissionError`` is also raised when you are trying to open/create a file but the first argument to ``open`` function is folder instead of file. .. GENERATED FROM PYTHON SOURCE LINES 124-128 FileNotFoundError --------------------- This error is raised when the the file that we are trying to open does not exist in the directory/path. .. GENERATED FROM PYTHON SOURCE LINES 128-132 .. code-block:: default # uncomment following 1 line # open("NonExistingFile", "r") # -> FileNotFoundError: [Errno 2] No such file or directory: 'NonExistingFile' .. GENERATED FROM PYTHON SOURCE LINES 133-138 IndexError ----------- This error is raised when try to access a value from a sequence based upon the index which is not available for that sequence. For example, for a list with three members, if we try to access its fourth member, we will get ``IndexError``. .. GENERATED FROM PYTHON SOURCE LINES 138-143 .. code-block:: default my_list = [1, 2, 3] # uncomment following line # my_list[3] # -> IndexError: list index out of range .. GENERATED FROM PYTHON SOURCE LINES 144-145 Same is true for tuples. .. GENERATED FROM PYTHON SOURCE LINES 145-151 .. code-block:: default my_tuple = (1, 2, 3) # uncomment following line # my_tuple[3] # -> IndexError: tuple index out of range .. GENERATED FROM PYTHON SOURCE LINES 152-154 There is another commonly encountered error i.e., ``AttributeError``. We are not introducing it here. It will discussed later in :ref:`sphx_glr_auto_examples_oop___getattr__.py`. .. GENERATED FROM PYTHON SOURCE LINES 156-164 Error handling ------------------ So what is the purpose of knowing all of these errors? Sometimes we would like to forecast/predict an error and bypass the error by applying the solution. In the function below, we would like to add a value in 2. However, if due to ``TypeError`` we can not do so, then we would first convert it to integer before adding it into 2. .. GENERATED FROM PYTHON SOURCE LINES 164-177 .. code-block:: default def add_number(val): try: val = val + 2 except TypeError: print('TypeError was encountered but bypassed') val = int(val) + 2 return val add_number(2) .. rst-class:: sphx-glr-script-out .. code-block:: none 4 .. GENERATED FROM PYTHON SOURCE LINES 178-180 .. code-block:: default add_number('2') .. rst-class:: sphx-glr-script-out .. code-block:: none TypeError was encountered but bypassed 4 .. GENERATED FROM PYTHON SOURCE LINES 181-183 Sometimes we want to handle/catch multiple exceptions. We can do this in one line by writing all the exceptions inside a tuple after ``except`` keyword. .. GENERATED FROM PYTHON SOURCE LINES 183-193 .. code-block:: default def multiple_exceptions(wname): try: out = float(wname.split('_')[2]) except (ValueError, IndexError) as e: raise Exception(f"{wname} raised ", e) return out .. GENERATED FROM PYTHON SOURCE LINES 194-195 Above, we want to catch ValueError and IndexError at the same time. .. GENERATED FROM PYTHON SOURCE LINES 195-199 .. code-block:: default # uncomment following line # multiple_exceptions("11_2.5.h5") # -> IndexError .. GENERATED FROM PYTHON SOURCE LINES 200-204 .. code-block:: default # uncomment following line # multiple_exceptions("11_2_5.h5") # -> ValueError .. GENERATED FROM PYTHON SOURCE LINES 205-208 .. code-block:: default multiple_exceptions("11_2_5") .. rst-class:: sphx-glr-script-out .. code-block:: none 5.0 .. GENERATED FROM PYTHON SOURCE LINES 209-212 Error handling is also used by printing out more useful error messages to the user. Suppose the package ``ai4water`` is not installed which may be required. Then instead of just throwing ``ModuleNotFoundError``, we can help the user by giving more helpful error message .. GENERATED FROM PYTHON SOURCE LINES 212-224 .. code-block:: default def better_error_message(): try: import ai4water except ModuleNotFoundError as e: raise ModuleNotFoundError(f"You must install ai4water using pip install ai4water \n{e}") return # uncomment following line # better_error_message() .. GENERATED FROM PYTHON SOURCE LINES 225-236 Custom Errors ----------------- We can create our own errors based upon our needs. Any new error must inherit from ``Exception`` class or its base classes. If at this stage you are uncomfortable with the concept of ``class`` or `base class`, you can jump to lessons of :ref:`sphx_glr_auto_examples_oop_introduction.py` and :ref:`sphx_glr_auto_examples_oop_inheritance.py` in :ref:`sphx_glr_auto_examples_oop` chapter to know about them. Below we create an error which will be raised if a value is above 256. .. GENERATED FROM PYTHON SOURCE LINES 236-247 .. code-block:: default class IllegalValue(Exception): def __init__(self, val): self.val = val def __str__(self): return f"val must be below 256 but it is {self.val}" value = 1000 .. GENERATED FROM PYTHON SOURCE LINES 248-249 We can invoke this as given below. .. GENERATED FROM PYTHON SOURCE LINES 249-254 .. code-block:: default # Uncomment following two lines # if value>256: # raise IllegalValue(value) .. GENERATED FROM PYTHON SOURCE LINES 255-263 **Note** Error messages are blessings in disguise. Whenever you get an error, you should consider yourself very lucky. Most of the learning happens in the process of understanding and resolving the errors. Without errors (and resolving them), the process of coding will look like copy paste and anything you learn will be forgotten very soon. So don't be afraid of errors. Embrace them with open heart and learn from them. .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.004 seconds) .. _sphx_glr_download_auto_examples_basics_exceptions.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/basics/exceptions.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: exceptions.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: exceptions.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_