Skip to content

Instantly share code, notes, and snippets.

@surabhiagarwal-in
Created February 26, 2021 08:51
Show Gist options
  • Save surabhiagarwal-in/a98306d73d04814a428815b15f195ce2 to your computer and use it in GitHub Desktop.
Save surabhiagarwal-in/a98306d73d04814a428815b15f195ce2 to your computer and use it in GitHub Desktop.
Created on Skills Network Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<center>\n",
" <img src=\"https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n",
"</center>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# **Exception Handling**\n",
"\n",
"Estimated time needed: **15** minutes\n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"- Understand exceptions \n",
"- Handle the exceptions\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Table of Contents\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- What is an Exception?\n",
"- Exception Handling\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* * *\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What is an Exception?\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this section you will learn about what an exception is and see examples of them.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Definition\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An exception is an error that occurs during the execution of code. This error causes the code to raise an exception and if not prepared to handle it will halt the execution of the code.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Examples\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run each piece of code and observe the exception raised\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"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<ipython-input-1-9e1622b385b6>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \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[0m\n\u001b[0m",
"\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
]
}
],
"source": [
"1/0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<code>ZeroDivisionError</code> occurs when you try to divide by zero.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'a' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-2-6ddcec040107>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'a' is not defined"
]
}
],
"source": [
"y = a + 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<code>NameError</code> in this case means that you tried to use the variable a when it was not defined.\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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<ipython-input-3-3f911ca4e3d3>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\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[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m10\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": [
"a = [1, 2, 3]\n",
"a[10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<code>IndexError</code> in this case occurs when you try to access data from a list using an index that does not exist for this list.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many more exceptions that are built into Python, here is a list of them [https://docs.python.org/3/library/exceptions.html](https://docs.python.org/3/library/exceptions.html?cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork-19487395&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ&cm_mmc=Email_Newsletter-_-Developer_Ed%2BTech-_-WW_WW-_-SkillsNetwork-Courses-IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork-19487395&cm_mmca1=000026UJ&cm_mmca2=10006555&cm_mmca3=M12345678&cvosrc=email.Newsletter.M12345678&cvo_campaign=000026UJ)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exception Handling\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this section you will learn how to handle exceptions to perform certain tasks and not halt the execution of your code.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A <code>try except</code> will allow you to execute code that might raise an exception and in the case of any exception or a specific one we can handle or catch the exception and execute specific code. This will allow us to continue the execution of our program even if there is an exception.\n",
"\n",
"Python tries to execute the code in the <code>try</code> block. In this case if there is any exception raised by the code in the <code>try</code> block it will be caught and the code block in the <code>except</code> block will be executed. After the code that comes after the try except will be executed.\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"ename": "IndentationError",
"evalue": "expected an indented block (<ipython-input-4-5647baae0eae>, line 5)",
"output_type": "error",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-4-5647baae0eae>\"\u001b[0;36m, line \u001b[0;32m5\u001b[0m\n\u001b[0;31m except:\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n"
]
}
],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except:\n",
" # code to execute if there is an exception\n",
" \n",
"# code that will still execute if there is an exception"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except Example\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example we are trying to divide a number given by the user, save the outcome in the variable <code>a</code>, and then we would like to print the result of the operation. When taking user input and dividing a number by it there are a couple of exceptions that can be raised. For example if we divide by zero, try running the following block of code, with <code>b</code> as a number an exception will only be Raised if <code>b</code>, is zero \n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please enter a number to divide a 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"There was an error\n"
]
}
],
"source": [
"a = 1\n",
"\n",
"try:\n",
" b = int(input(\"Please enter a number to divide a\"))\n",
" a = a/b\n",
" print(\"Success a=\",a)\n",
"except:\n",
" print(\"There was an error\")\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except Specific\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A specific try except allows you to catch certain exceptions and also execute certain code depending on the exception. This is useful if you do not want to deal with some exceptions and the execution should halt, it can also help you find errors in your code that you might not know about, and it can help you differentiate responses to different exceptions. In this case the code after the try except might not run depending on the error.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>do not run, just to illustrate</b>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except (ZeroDivisionError, NameError):\n",
" # code to execute if there is an exception of the given types\n",
" \n",
"# code that will execute if there is no exception or a one that we are handling"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except ZeroDivisionError:\n",
" # code to execute if there is a ZeroDivisionError\n",
"except NameError:\n",
" # code to execute if there is a NameError\n",
" \n",
"# code that will execute if there is no exception or a one that we are handling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also have an empty except at the end to catch an unexpected exception:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>do not run, just to illustrate</b>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except ZeroDivisionError:\n",
" # code to execute if there is a ZeroDivisionError\n",
"except NameError:\n",
" # code to execute if there is a NameError\n",
"except:\n",
" # code to execute if ther is any exception\n",
" \n",
"# code that will execute if there is no exception or a one that we are handling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except Specific Example\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is the same example as above, but now we will add differentiated messages depending on the exception letting the user know what is wrong with the input.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please enter a number to divide a 89\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Success a= 0.011235955056179775\n"
]
}
],
"source": [
"a = 1\n",
"\n",
"try:\n",
" b = int(input(\"Please enter a number to divide a\"))\n",
" a = a/b\n",
" print(\"Success a=\",a)\n",
"except ZeroDivisionError:\n",
" print(\"The number you provided cant divide 1 because it is 0\")\n",
"except ValueError:\n",
" print(\"You did not provide a number\")\n",
"except:\n",
" print(\"Something went wrong\")\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except Else and Finally\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<code>else</code> allows one to check if there was no exception when executing the try block. This is useful when we want to execute something only if there were no errors.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>do not run, just to illustrate</b>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except ZeroDivisionError:\n",
" # code to execute if there is a ZeroDivisionError\n",
"except NameError:\n",
" # code to execute if there is a NameError\n",
"except:\n",
" # code to execute if ther is any exception\n",
"else:\n",
" # code to execute if there is no exception\n",
" \n",
"# code that will execute if there is no exception or a one that we are handling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<code>finally</code> allows us to always execute something even if there is an exception or not. This is usually used to signify the end of the try except.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# potential code before try catch\n",
"\n",
"try:\n",
" # code to try to execute\n",
"except ZeroDivisionError:\n",
" # code to execute if there is a ZeroDivisionError\n",
"except NameError:\n",
" # code to execute if there is a NameError\n",
"except:\n",
" # code to execute if ther is any exception\n",
"else:\n",
" # code to execute if there is no exception\n",
"finally:\n",
" # code to execute at the end of the try except no matter what\n",
" \n",
"# code that will execute if there is no exception or a one that we are handling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try Except Else and Finally Example\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You might have noticed that even if there is an error the value of a is always printed. Lets use the else and print the value of a only if there is no error.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1\n",
"\n",
"try:\n",
" b = int(input(\"Please enter a number to divide a\"))\n",
" a = a/b\n",
"except ZeroDivisionError:\n",
" print(\"The number you provided cant divide 1 because it is 0\")\n",
"except ValueError:\n",
" print(\"You did not provide a number\")\n",
"except:\n",
" print(\"Something went wrong\")\n",
"else:\n",
" print(\"success a=\",a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now lets let the user know that we are done processing their answer. Using the <code>finally</code> lets add a print.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1\n",
"\n",
"try:\n",
" b = int(input(\"Please enter a number to divide a\"))\n",
" a = a/b\n",
"except ZeroDivisionError:\n",
" print(\"The number you provided cant divide 1 because it is 0\")\n",
"except ValueError:\n",
" print(\"You did not provide a number\")\n",
"except:\n",
" print(\"Something went wrong\")\n",
"else:\n",
" print(\"success a=\",a)\n",
"finally:\n",
" print(\"Processing Complete\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Authors\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Change Log\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"| ----------------- | ------- | ---------- | ---------------------------- |\n",
"| 2020-09-02 | 2.0 | Simran | Template updates to the file |\n",
"| | | | |\n",
"| | | | |\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"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.6.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment