|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "id": "4438521d-a198-4af9-b634-448e65fdc540", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "## Try-Except Statement\n", |
| 9 | + "In Python, exceptions can be handled using try-except blocks. \n", |
| 10 | + "* If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. \n", |
| 11 | + "* The try block must be followed by the except statement, which contains a block of code that will be executed in case there is some exception in the try block. \n", |
| 12 | + "* We can thus choose what operations to perform once we have caught the exception" |
| 13 | + ] |
| 14 | + }, |
| 15 | + { |
| 16 | + "cell_type": "markdown", |
| 17 | + "id": "aae2b4d8-d0e3-431b-ad11-7f63c3540186", |
| 18 | + "metadata": {}, |
| 19 | + "source": [ |
| 20 | + "<center><img src=\"https://files.realpython.com/media/try_except.c94eabed2c59.png\" style=\"max-width:650px; height:auto\"></center>" |
| 21 | + ] |
| 22 | + }, |
| 23 | + { |
| 24 | + "cell_type": "markdown", |
| 25 | + "id": "0f743db4-d2aa-4874-acfb-c0d81414c9cb", |
| 26 | + "metadata": {}, |
| 27 | + "source": [ |
| 28 | + "**Syntax:**\n", |
| 29 | + "```python\n", |
| 30 | + "try:\n", |
| 31 | + " # Code that may raise an exception\n", |
| 32 | + " # ...\n", |
| 33 | + "except SomeException as e:\n", |
| 34 | + " # Code to handle the exception\n", |
| 35 | + " # ...\n", |
| 36 | + "```\n", |
| 37 | + "\n", |
| 38 | + "**Example:**" |
| 39 | + ] |
| 40 | + }, |
| 41 | + { |
| 42 | + "cell_type": "code", |
| 43 | + "execution_count": 1, |
| 44 | + "id": "9088a0a5-182b-442b-9bcf-c0e9a1a059d1", |
| 45 | + "metadata": { |
| 46 | + "tags": [] |
| 47 | + }, |
| 48 | + "outputs": [ |
| 49 | + { |
| 50 | + "name": "stdout", |
| 51 | + "output_type": "stream", |
| 52 | + "text": [ |
| 53 | + "The list item is: a\n", |
| 54 | + "Oops! <class 'ValueError'> occured.\n", |
| 55 | + "\n", |
| 56 | + "The list item is: 0\n", |
| 57 | + "Oops! <class 'ZeroDivisionError'> occured.\n", |
| 58 | + "\n", |
| 59 | + "The list item is: 2\n", |
| 60 | + "The reciprocal of 2 is 0.5\n" |
| 61 | + ] |
| 62 | + } |
| 63 | + ], |
| 64 | + "source": [ |
| 65 | + "myList = [\"a\", 0, 2]\n", |
| 66 | + "\n", |
| 67 | + "for i in myList:\n", |
| 68 | + " try:\n", |
| 69 | + " print(\"The list item is:\", i)\n", |
| 70 | + " reciprocal = 1/int(i)\n", |
| 71 | + " print(\"The reciprocal of\", i, \"is\", reciprocal)\n", |
| 72 | + " \n", |
| 73 | + " except Exception as e: #Using Exception class\n", |
| 74 | + " print(\"Oops!\", e.__class__, \"occured.\")\n", |
| 75 | + " print()" |
| 76 | + ] |
| 77 | + }, |
| 78 | + { |
| 79 | + "cell_type": "markdown", |
| 80 | + "id": "d6cd5ce9-65d2-4db9-91fb-c7815d70b16e", |
| 81 | + "metadata": {}, |
| 82 | + "source": [ |
| 83 | + "* In this program, we loop through the values of a list 'myList'. \n", |
| 84 | + "* As previously mentioned, the portion that can cause an exception is placed inside the try block. \n", |
| 85 | + "* If no exception occurs, the except block is skipped and normal flow continues (for last value). \n", |
| 86 | + "* But if any exception occurs, it is caught by the except block (first and second values).\n", |
| 87 | + "* Here, we print the name of the exception using the exc_info() function inside sys module. \n", |
| 88 | + "* We can see that element “a” causes ValueError and 0 causes ZeroDivisionError." |
| 89 | + ] |
| 90 | + }, |
| 91 | + { |
| 92 | + "cell_type": "markdown", |
| 93 | + "id": "1e1674a9-286f-42b6-b707-26dfe2d0e7fb", |
| 94 | + "metadata": {}, |
| 95 | + "source": [ |
| 96 | + "### Catching Specific Exceptions in Python\n", |
| 97 | + "* In the above example, we did not mention any specific exception in the **except** clause. \n", |
| 98 | + "* This is not a good programming practice as it will catch all exceptions and handle every case in the same way. \n", |
| 99 | + "* We can specify which exceptions an **except** clause should catch. \n", |
| 100 | + "* A try clause can have any number of **except** clauses to handle different exceptions, however, only one will be executed in case an exception occurs. \n", |
| 101 | + "* You can use multiple **except** blocks for different types of exceptions. \n", |
| 102 | + "* We can even use a tuple of values to specify multiple exceptions in an **except** clause. Here is an example to understand this better:" |
| 103 | + ] |
| 104 | + }, |
| 105 | + { |
| 106 | + "cell_type": "markdown", |
| 107 | + "id": "e97b019d-0a77-45ba-af25-ddb49eb95cdb", |
| 108 | + "metadata": {}, |
| 109 | + "source": [ |
| 110 | + "**Example:**" |
| 111 | + ] |
| 112 | + }, |
| 113 | + { |
| 114 | + "cell_type": "code", |
| 115 | + "execution_count": 2, |
| 116 | + "id": "a94e3590-95fb-4687-9181-6e55ea6f17df", |
| 117 | + "metadata": { |
| 118 | + "tags": [] |
| 119 | + }, |
| 120 | + "outputs": [ |
| 121 | + { |
| 122 | + "name": "stdout", |
| 123 | + "output_type": "stream", |
| 124 | + "text": [ |
| 125 | + "Arithmetic Exception\n" |
| 126 | + ] |
| 127 | + } |
| 128 | + ], |
| 129 | + "source": [ |
| 130 | + "try:\n", |
| 131 | + " a = 10/0\n", |
| 132 | + " print(a)\n", |
| 133 | + " \n", |
| 134 | + "except (ArithmeticError, IOError):\n", |
| 135 | + " print(\"Arithmetic Exception\")" |
| 136 | + ] |
| 137 | + } |
| 138 | + ], |
| 139 | + "metadata": { |
| 140 | + "kernelspec": { |
| 141 | + "display_name": "Python 3 (ipykernel)", |
| 142 | + "language": "python", |
| 143 | + "name": "python3" |
| 144 | + }, |
| 145 | + "language_info": { |
| 146 | + "codemirror_mode": { |
| 147 | + "name": "ipython", |
| 148 | + "version": 3 |
| 149 | + }, |
| 150 | + "file_extension": ".py", |
| 151 | + "mimetype": "text/x-python", |
| 152 | + "name": "python", |
| 153 | + "nbconvert_exporter": "python", |
| 154 | + "pygments_lexer": "ipython3", |
| 155 | + "version": "3.10.9" |
| 156 | + } |
| 157 | + }, |
| 158 | + "nbformat": 4, |
| 159 | + "nbformat_minor": 5 |
| 160 | +} |
0 commit comments