{ "cells": [ { "cell_type": "markdown", "id": "ca09f7e7", "metadata": {}, "source": [ "--- \n", " \n", "\n", "

Department of Data Science

\n", "

Course: Tools and Techniques for Data Science

\n", "\n", "---\n", "

Instructor: Muhammad Arif Butt, Ph.D.

" ] }, { "cell_type": "markdown", "id": "19663b8b", "metadata": {}, "source": [ "

Lecture 2.13

" ] }, { "cell_type": "markdown", "id": "8258d1ca", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "037b9831", "metadata": {}, "source": [ "## _Python Exceptions.ipynb_" ] }, { "cell_type": "markdown", "id": "27711bd2", "metadata": {}, "source": [ "## Learning agenda of this notebook\n", "1. What are syntax errors?\n", "2. What are exceptions?\n", "3. How to handle exceptions?\n", "4. Types of exceptions in Python\n", "5. Multiple `except` clauses\n", "6. Python `else` clause and `finally` keyword\n", "7. Python `raise` keyword to raise an Exception\n", "8. Python `assert` keyword as a sanity check" ] }, { "cell_type": "markdown", "id": "3aa307b8", "metadata": {}, "source": [ "## 1. What are Syntax Errors??\n", "- **Syntax Errors or Parsing Errors:** are errors that are raised before the program/script actually starts its execution. Some common parsing errors in Python are: incorrect indentation, leaving out a symbol (e.g., collon or bracket), empty block. " ] }, { "cell_type": "code", "execution_count": 1, "id": "c7bb9b30", "metadata": { "scrolled": true }, "outputs": [ { "ename": "SyntaxError", "evalue": "unmatched ')' (3938186187.py, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/3938186187.py\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m print(1/0))\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unmatched ')'\n" ] } ], "source": [ "# Example 1: An example of syntax Error (An unmatched bracket)\n", "print(1/0))" ] }, { "cell_type": "markdown", "id": "1beadc90", "metadata": {}, "source": [ "**Note that in case of a syntax error in your program, none of the statement is executed**" ] }, { "cell_type": "code", "execution_count": 2, "id": "50d834be", "metadata": {}, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (2308473987.py, line 5)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/2308473987.py\"\u001b[0;36m, line \u001b[0;32m5\u001b[0m\n\u001b[0;31m print(\"Hello\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "# Example 2: An example of syntax Error (Incorrect Indentation)\n", "1/0 # note this error is not raised\n", "print('This will not be printed')\n", "if True:\n", "print(\"Hello\")" ] }, { "cell_type": "markdown", "id": "ba23fe91", "metadata": {}, "source": [ "**Note that in case of a syntax error in your program, none of the statement is executed**" ] }, { "cell_type": "markdown", "id": "5bb06d31", "metadata": {}, "source": [ "## 2. What are Exceptions?\n", "- **Exceptions:** An exception is an error that happens during the execution of a syntactically correct program, (e.g., division by zero), that disrupts the normal flow of program execution. When an exception occurs, Python generates an appropriate exception object (representing error)" ] }, { "cell_type": "code", "execution_count": 3, "id": "350f4af0", "metadata": {}, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/1355514053.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Example 1: ZeroDivisionError is an exception that is raised when you perform a division by zero.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "# Example 1: ZeroDivisionError is an exception that is raised when you perform a division by zero.\n", "print(1/0)" ] }, { "cell_type": "code", "execution_count": 4, "id": "3b9c12e7", "metadata": {}, "outputs": [ { "ename": "IndexError", "evalue": "list index out of range", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/3576555205.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Example 2: IndexError is an exception that is raised when trying to access a list index out of range\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mmylist\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m33\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m21\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmylist\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m8\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mIndexError\u001b[0m: list index out of range" ] } ], "source": [ "# Example 2: IndexError is an exception that is raised when trying to access a list index out of range\n", "mylist = [5, 33, 21]\n", "print(mylist[8])" ] }, { "cell_type": "markdown", "id": "104aed1b", "metadata": {}, "source": [ "**Let us suppose we have written a program that prompts the user to enter temperature in Farhenheit and converts it into Celsius and it is working perfectly fine**" ] }, { "cell_type": "code", "execution_count": 5, "id": "91ef64d4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter Fahrenheit Temprature: abc\n" ] }, { "ename": "ValueError", "evalue": "could not convert string to float: 'abc'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/445056864.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m# Seems to work perfectly fine\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mfar\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Enter Fahrenheit Temprature: \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mcel\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mfar\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m32.0\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m5.0\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m9.0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mcel\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: could not convert string to float: 'abc'" ] } ], "source": [ "# Example 3: A program that prompts the user to enter temperature in Farhenheit and converts it into Celsius\n", "# Seems to work perfectly fine\n", "\n", "far = float(input(\"Enter Fahrenheit Temprature: \"))\n", "cel = (far - 32.0) * 5.0/9.0\n", "print (cel)" ] }, { "cell_type": "markdown", "id": "d45f50e2", "metadata": {}, "source": [ "**What happens if a user enter a string instead of a number**" ] }, { "cell_type": "markdown", "id": "5ec1d7d2", "metadata": {}, "source": [ "## 3. How to Handle Exceptions?\n", " \n", "\n", "- In Python **try** and **except** keywords are used to catch and handle exceptions respectively. \n", "- Instructions that can raise exceptions are kept inside the `try block` and the instructions that handle the exception are written inside `except block`. \n", "- The code inside the `except block` will execute only in case, when the program encounters some error in the preceding `try block`.\n", "- Let us handle the exception `ValueError` that is raised in above program" ] }, { "cell_type": "code", "execution_count": 6, "id": "32e9af8f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter Fahrenheit Temprature: abc\n", "An error occurred\n", "GR8 going\n" ] } ], "source": [ "# Example 1: Handle ValueError (if the user inputs a string instead of number)\n", "try:\n", " far = float(input(\"Enter Fahrenheit Temprature: \"))\n", " cel = (far - 32.0) * 5.0/9.0\n", " print (cel)\n", "\n", "# This block will exectue the program without any crash \n", "except:\n", " print(\"An error occurred\")\n", "\n", "print(\"GR8 going\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "24ae669f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "An error occurred\n" ] } ], "source": [ "# Example 2: Three errors are there in the try block: ZeroDivisionError, NameError, and TypeError\n", "# A try clause is executed up until the point, where the first exception is encountered\n", "try:\n", "# z = 45 / 0\n", " # print(z)\n", " a = 34 + 'hello'\n", " \n", "# This block will exectue the program without any crash\n", "except:\n", " print(\"An error occurred\")" ] }, { "cell_type": "markdown", "id": "73e10931", "metadata": {}, "source": [ "**The above example of try-except statement is good as it is simple and can catch all types of exception. However, it does not help the programmer identify the root cause of the problem**" ] }, { "cell_type": "markdown", "id": "954ccc09", "metadata": {}, "source": [ "## 4. Types of Exceptions in Python\n", "- There are several built-in exceptions in Python that are raised when an error occur. Some common examples of Python built-in exceptions are:\n", " - **ZeroDivisionError** is raised when you perform a division by zero.\n", " - **ValueError** is raised when a function or built-in operation receives an argument that has the right type but an inappropriate value.\n", " - **NameError** is raised when the Python interpreter encounters a symbol that does not exist.\n", " - **TypeError** is raised when you try performing an operation on unsupported types (e.g., 5 + 'hello').\n", " - **IndexError** is raised when you try to refer a sequence which is out of range.\n", " - **IOError** is raised when an IO operation fails, e.g., trying to open a file that do not exist.\n", " - **EOFError** is raised when built-in function like input() hits an end of file condition, without reading any data.\n", " - **ImportError** is raised when an import statement fails to find the module.\n", " - **AssertionError** is raised when an assert statement fails (an assert statement allows you to create simple debug message outputs based on simple logical assertions).\n", ">- When an exception occurs the appropriate Exception class object is sent to the `except` clause, that we can receive as an argument. ```except Exception as e: ```\n", ">- The Exception class object received contains additional information about the raised exception, so as to handle it accordingly." ] }, { "cell_type": "code", "execution_count": 8, "id": "ef4a15c7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception occured: unsupported operand type(s) for +: 'int' and 'str'\n" ] } ], "source": [ "# Example code that specifies the type of exception raised\n", "try:\n", " #z = 45 / 0\n", " # print(z)\n", " a = 34 + 'hello'\n", " \n", "\n", "except Exception as e:\n", " print(\"Exception occured: \", e)" ] }, { "cell_type": "markdown", "id": "710fc4dd", "metadata": {}, "source": [ "## 5. Multiple `except` Clauses\n", "- Inside a try block, there may be different exceptions that can be raised.\n", "- Being a programmer we would like to write different handlers for different exceptions.\n", "- To handle this, we can have multiple except blocks for one try block.\n", "- The except block corresponding to the first raised exception will be executed. \n", "- Note: In Python there is no concept of default catch block as in C++" ] }, { "cell_type": "code", "execution_count": 9, "id": "d112145f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ModuleNotFoundError Occurred and Handled\n" ] } ], "source": [ "try:\n", " # z = 45 / 0\n", " #print(z)\n", " #a = 34 + 'hello'\n", " #list1 = [1, 5, 9]\n", " #print(list1[3])\n", " import kakamanna #ModuleNotFounderror\n", "except ZeroDivisionError:\n", " print(\"ZeroDivisionError Occurred and Handled\")\n", "except NameError:\n", " print(\"NameError Occurred and Handled\")\n", "except TypeError:\n", " print(\"TypeError Occurred and Handled\")\n", "except IndexError:\n", " print(\"IndexError Occurred and Handled\")\n", "except ModuleNotFoundError:\n", " print(\"ModuleNotFoundError Occurred and Handled\")" ] }, { "cell_type": "code", "execution_count": null, "id": "3121031c", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "1b4c8ab0", "metadata": {}, "source": [ "## 6. Python `try-except` with `else` Clause and `finally` Keyword\n", " " ] }, { "cell_type": "markdown", "id": "9d831a7f", "metadata": {}, "source": [ "### a. The `else` Clause\n", "- The **`else clause`** is used if you want to execute a piece of code that should execute when no exception is raised.\n", "- The **`else clause`** in the try-except block must be placed after all the except clauses.\n", "- The code enters the else block only if the try clause does not raise an exception." ] }, { "cell_type": "code", "execution_count": 10, "id": "47ee21e1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List Elements are: [1, 5, 9]\n", "ZeroDivisionError Occurred and Handled\n" ] } ], "source": [ "try:\n", " list1 = [1, 5, 9]\n", " print(\"List Elements are: \", list1)\n", " 5/0\n", "\n", "except ZeroDivisionError:\n", " print(\"ZeroDivisionError Occurred and Handled\")\n", "except NameError:\n", " print(\"NameError Occurred and Handled\")\n", "except TypeError:\n", " print(\"TypeError Occurred and Handled\")\n", "except IndexError:\n", " print(\"IndexError Occurred and Handled\")\n", "else: \n", " print(\"This will execute if try clause does not raise an exception\")" ] }, { "cell_type": "markdown", "id": "4141c81b", "metadata": {}, "source": [ "### b. The `finally` Keyword\n", "- The **`finally clause`** is used to execute a piece of code that must execute, whether the `try-block` raise an exception or not.\n", "- The **`finally clause`** in the `try-except` block must be placed after all the `except` clauses, even after the `else` clause. \n", "- Used to define clean-up actions that must be executed under all circumstances." ] }, { "cell_type": "code", "execution_count": 11, "id": "d20ab9d9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List Elements are: [1, 5, 9]\n", "ZeroDivisionError Occurred and Handled\n", "This will always be executed\n" ] } ], "source": [ "try:\n", " list1 = [1, 5, 9]\n", " print(\"List Elements are: \", list1)\n", " 5/0\n", "\n", "except ZeroDivisionError:\n", " print(\"ZeroDivisionError Occurred and Handled\")\n", "except NameError:\n", " print(\"NameError Occurred and Handled\")\n", "except TypeError:\n", " print(\"TypeError Occurred and Handled\")\n", "except IndexError:\n", " print(\"IndexError Occurred and Handled\")\n", "else: \n", " print(\"This will execute if try clause does not raise an exception\")\n", "finally:\n", " print(\"This will always be executed\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c3c2b9fa", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "10542042", "metadata": {}, "source": [ "## 7. Python `raise` Keword to Raise an Exception\n", "- The Python `raise` keyword is used to raise an exception.\n", "- You can define what kind of exception to raise, and the text to print to the user." ] }, { "cell_type": "code", "execution_count": 12, "id": "1d34ca97", "metadata": {}, "outputs": [ { "ename": "Exception", "evalue": "x should not be negative. The value of age was -1", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/1228122984.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m#age = 5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mage\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"x should not be negative. The value of age was {}\"\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mformat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Program continues as age is positive\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mException\u001b[0m: x should not be negative. The value of age was -1" ] } ], "source": [ "# Example 1: Raise an exception if x is negative and display an appropriate message to user as to what went wrong\n", "age = -1\n", "#age = 5\n", "if age < 0:\n", " raise Exception(\"x should not be negative. The value of age was {}\".format(age))\n", "print(\"Program continues as age is positive\")" ] }, { "cell_type": "code", "execution_count": null, "id": "a2ae1c75", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 13, "id": "9b221010", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "Only integers are allowed", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/3477007658.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m#x = 5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Only integers are allowed\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Program continues as x is a number\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: Only integers are allowed" ] } ], "source": [ "#Example 2: Raise an exception if x is not a number and display an appropriate message\n", "x = \"hello\"\n", "#x = 5\n", "if not type(x) is int:\n", " raise TypeError(\"Only integers are allowed\")\n", "print(\"Program continues as x is a number\")" ] }, { "cell_type": "markdown", "id": "1b6c472d", "metadata": {}, "source": [ ">In above examples, when we used the `raise` keyword, whenever the condition evaluated to true, the exception was raised and our program crashed midway" ] }, { "cell_type": "code", "execution_count": null, "id": "9b41850e", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "83f72057", "metadata": {}, "source": [ "## 8. Python `assert` Keyword\n", "- Instead for waiting for our program to crash midway, right in the beginning of our program we can check the conditions using the `assert` statement.\n", "- An `assert` statement is passed two comma separated arguments, the first is a condition, which if evaluates to False, the exception `AssertionError` is raised and the second argument is passed to it.\n", "- If the condition evaluates to True, program continues its execution.\n", "- You can think of `assert` statement as:\n", ">- testing an expression, and if the result is false, raise an exception (AssertionError).\n", ">- a sanity-check that you can turn on, or turn off when you are done with your testing of the program." ] }, { "cell_type": "code", "execution_count": 14, "id": "0f2e56fa", "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "age should be positive", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/3921261554.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m#age = 5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32massert\u001b[0m \u001b[0mage\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;34m,\u001b[0m \u001b[0;34m'age should be positive'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Program continues as age is positive\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mAssertionError\u001b[0m: age should be positive" ] } ], "source": [ "# Example 1:\n", "age = -1\n", "#age = 5\n", "assert age > 0 , 'age should be positive'\n", "print(\"Program continues as age is positive\")" ] }, { "cell_type": "code", "execution_count": 15, "id": "e5a924b2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Program continues as x is a number\n" ] } ], "source": [ "#Example 2: \n", "#x = \"hello\"\n", "x = 5\n", "assert type(x) is int, 'x must be integer'\n", "print(\"Program continues as x is a number\")" ] }, { "cell_type": "code", "execution_count": null, "id": "fb4a7d11", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 16, "id": "39ed8c64", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'darwin'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sys\n", "sys.platform" ] }, { "cell_type": "code", "execution_count": null, "id": "c0245bd9", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 17, "id": "8a89be12", "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "This code runs only on Windows", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_28236/2705886563.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m#Example 3:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0msys\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32massert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'win32'\u001b[0m \u001b[0;32min\u001b[0m \u001b[0msys\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mplatform\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"This code runs only on Windows\"\u001b[0m \u001b[0;31m# On Mac this will raise AssertionError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;31m#assert('darwin' in sys.platform), \"This code runs only on Mac\" # On Mac this will succeed\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mAssertionError\u001b[0m: This code runs only on Windows" ] } ], "source": [ "#Example 3: \n", "import sys\n", "assert('win32' in sys.platform), \"This code runs only on Windows\" # On Mac this will raise AssertionError\n", "#assert('darwin' in sys.platform), \"This code runs only on Mac\" # On Mac this will succeed\n", "\n", "print(\"Program continues...\")" ] }, { "cell_type": "code", "execution_count": null, "id": "12e706d1", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "3c7cc6ce", "metadata": {}, "source": [ "## Check your Concepts\n", "\n", "Try answering the following questions to test your understanding of the topics covered in this notebook:\n", "\n", "1. What are exceptions in Python? When do they occur?\n", "2. How are exceptions different from syntax errors?\n", "3. What are the different types of in-built exceptions in Python? Where can you learn about them?\n", "4. How do you prevent the termination of a program due to an exception?\n", "5. What is the purpose of the `try`-`except` statements in Python?\n", "6. What is the syntax of the `try`-`except` statements? Give an example.\n", "7. What happens if an exception occurs inside a `try` block?\n", "8. How do you handle two different types of exceptions using `except`? Can you have multiple `except` blocks under a single `try` block?\n", "9. How do you create an `except` block to handle any type of exception?\n", "10. Illustrate the usage of `try`-`except` inside a function with an example.\n", "11. Differentiate between checked and unchecked exceptions\n", " - **Checked Exceptions** are the exceptions which occur at compile time (e.g., file not found, no such function). Since Python is not compiled, so checked exceptions don't make much sense.\n", " - **Unchecked Exception** are the exceptions which are not checked by the compiler (e.g., arithmetic exception, array out of bound). If not handled by programmer properly, the program terminate at runtime. \n", "12. Dig out details about User-Defined Exceptions. Python also allows you to create your own exception classes by deriving them from the standard built-in Exception class. This is useful when you need to display more specific information when an exception is caught. Dig out details about user-defined exceptions from this link:https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions" ] }, { "cell_type": "code", "execution_count": null, "id": "e1cb9d94", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }