{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 011_exceptions\n", "\n", "[Source](https://github.com/iArunava/Python-TheNoTheoryGuide/)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Simple exceptions\n", "''' Here are a few exceptions, try executing one while others are commented'''\n", "print (5/0) # ZeroDivisionError\n", "print (\"string\" + 343) # TypeError\n", "file = open (\"./test.txt\") # FileNotFoundError" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Simple try-catch to avoid Exceptions\n", "try:\n", " print (5/0)\n", "except ZeroDivisionError:\n", " print (\"Cannot Divide by zero\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The else block\n", "# If the try block executes successfully, then the else block is executed\n", "deno = 1\n", "\n", "try:\n", " print (5/deno)\n", "except ZeroDivisionError:\n", " print (\"Deno is zero.\")\n", "else:\n", " print (\"Deno is not Zero.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Handle expection and not do anything\n", "deno = 0\n", "\n", "try:\n", " print (5/deno)\n", "except ZeroDivisionError:\n", " pass\n", "else:\n", " print (\"Deno not Zero.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Catch expection without explicitly knowing the type of exception\n", "deno = 1\n", "\n", "try:\n", " ''' Here are a few exceptions, try executing one while others are commented'''\n", " print (5/deno)\n", " print (\"string\" + 343)\n", " file = open (\"./test.txt\")\n", "except:\n", " print (\"Some exception!\")\n", "else:\n", " print (\"The try somehow executed completely!\\nDid you comment all lines?\")" ] } ], "metadata": { "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.6.3" } }, "nbformat": 4, "nbformat_minor": 2 }