{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/05_Python_Files)**\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Errors and Built-in Exceptions\n", "\n", "In this class, you will learn about different types of errors and exceptions that are built-in to Python. They are raised whenever the Python interpreter encounters errors.\n", "\n", "We can make certain mistakes while writing a program that lead to errors when we try to run it. A python program terminates as soon as it encounters an unhandled error. These errors can be broadly classified into two classes:\n", "\n", "1. Syntax errors\n", "2. Logical errors (Exceptions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Python Syntax Errors\n", "\n", "Error caused by not following the proper structure (syntax) of the language is called **syntax error** or **parsing error**.\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:39:26.584572Z", "start_time": "2021-06-18T15:39:26.566021Z" }, "scrolled": true }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m if a < 3\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "if a < 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As shown in the example, an arrow indicates where the parser ran into the syntax error.\n", "\n", "We can notice here that a colon **`:`** is missing in the **`if`** statement." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Python Logical Errors (Exceptions)\n", "\n", "Errors that occur at runtime (after passing the syntax test) are called **exceptions** or **logical errors**.\n", "\n", "For instance, they occur when we try to open a file(for reading) that does not exist (**`FileNotFoundError`**), try to divide a number by zero (**`ZeroDivisionError`**), or try to import a module that does not exist (**`ImportError`**).\n", "\n", "Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.\n", "\n", "Let's look at how Python treats these errors:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:39:28.907309Z", "start_time": "2021-06-18T15:39:28.612394Z" } }, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;36m1\u001b[0m \u001b[1;33m/\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "1 / 0" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:39:32.662651Z", "start_time": "2021-06-18T15:39:32.644100Z" } }, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'imaginary.txt'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"imaginary.txt\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'imaginary.txt'" ] } ], "source": [ "open(\"imaginary.txt\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Built-in Exceptions\n", "\n", "Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in **`local()`** function as follows:\n", "\n", "```python\n", "print(dir(locals()['__builtins__']))\n", "```\n", "\n", "**`locals()['__builtins__']`** will return a module of built-in exceptions, functions, and attributes. **`dir`** allows us to list these attributes as strings.\n", "\n", "Some of the common built-in exceptions in Python programming along with the error that cause them are listed below:\n", "\n", "| Exception | Cause of Error |\n", "|:----| :--- |\n", "| **`AssertionError`** | Raised when an **`assert`** statement fails. | \n", "| **`AttributeError`** | Raised when attribute assignment or reference fails. | \n", "| **`EOFError`** | Raised when the **`input()`** function hits end-of-file condition. | \n", "| **`FloatingPointError`** | Raised when a floating point operation fails. | \n", "| **`GeneratorExit`** | Raise when a generator's **`close()`** method is called. | \n", "| **`ImportError`** | Raised when the imported module is not found. | \n", "| **`IndexError`** | Raised when the index of a sequence is out of range. | \n", "| **`KeyError`** | Raised when a key is not found in a dictionary. | \n", "| **`KeyboardInterrupt`** | Raised when the user hits the interrupt key (**`Ctrl+C`** or **`Delete`**). | \n", "| **`MemoryError`** | Raised when an operation runs out of memory. | \n", "| **`NameError`** | Raised when a variable is not found in local or global scope. | \n", "| **`NotImplementedError`** | Raised by abstract methods. | \n", "| **`OSError`** | Raised when system operation causes system related error. | \n", "| **`OverflowError`** | Raised when the result of an arithmetic operation is too large to be represented. | \n", "| **`ReferenceError`** | Raised when a weak reference proxy is used to access a garbage collected referent. | \n", "| **`RuntimeError`** | Raised when an error does not fall under any other category. | \n", "| **`StopIteration`** | Raised by **`next()`** function to indicate that there is no further item to be returned by iterator. | \n", "| **`SyntaxError`** | Raised by parser when syntax error is encountered. | \n", "| **`IndentationError`** | Raised when there is incorrect indentation. | \n", "| **`TabError`** | Raised when indentation consists of inconsistent tabs and spaces. | \n", "| **`SystemError`** | Raised when interpreter detects internal error. | \n", "| **`SystemExit`** | Raised by **`sys.exit()`** function. | \n", "| **`TypeError`** | Raised when a function or operation is applied to an object of incorrect type. | \n", "| **`UnboundLocalError`** | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. | \n", "| **`UnicodeError`** | Raised when a Unicode-related encoding or decoding error occurs. | \n", "| **`UnicodeEncodeError`** | Raised when a Unicode-related error occurs during encoding. | \n", "| **`UnicodeDecodeError`** | Raised when a Unicode-related error occurs during decoding. | \n", "| **`UnicodeTranslateError`** | Raised when a Unicode-related error occurs during translating. | \n", "| **`ValueError`** | Raised when a function gets an argument of correct type but improper value. | \n", "| **`ZeroDivisionError`** | Raised when the second operand of division or modulo operation is zero. | " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If required, we can also define our own exceptions in Python. To learn more about them, visit Python **[User-defined Exceptions](https://github.com/milaan9/05_Python_Files/blob/main/005_Python_User_defined_Exceptions.ipynb)**.\n", "\n", "We can handle these built-in and user-defined exceptions in Python using **`try`**, **`except`** and **`finally`** statements. To learn more about them, visit **[Python try, except and finally statements](https://github.com/milaan9/05_Python_Files/blob/main/004_Python_Exceptions_Handling.ipynb)**." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }