{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "###
San Jose State University
Department of Applied Data Science

**DATA 200
Computational Programming for Data Analytics**

Spring 2024
Instructor: Ron Mak
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 9.9 finally Clause\n", "### The `finally` Clause of the `try` Statement\n", "#### If there is a `finally` clause, its suite will **always** execute, whether or not there was an exception raised. A very good use of a `finally` clause is one that **closes a file** that was opened in the `try` suite." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " print('try suite with no exceptions raised')\n", "except:\n", " print('this will not execute')\n", "else:\n", " print('else executes because no exceptions in the try suite')\n", "finally: \n", " print('finally always executes')\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " print('try suite that raises an exception')\n", " int('hello')\n", " print('this will not execute')\n", "except ValueError:\n", " print('a ValueError occurred')\n", "else:\n", " print('else will not execute because an exception occurred')\n", "finally: \n", " print('finally always executes')\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Raise Early, Handle Late\n", "\n", "#### If a function raises an exception that the function doesn't handle, the exception \"propagates\" up the call chain to the caller.\n", "#### A function should handle an exception if it can really remedy the error. Otherwise, the best course of action is to allow the exception to propagate up the call chain until there is a competent handler for the exception." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def convert_to_int(str):\n", " return int(str)\n", " \n", "def do_conversion(str):\n", " print(f\"Calling convert_to_int('{str}') ... \", end='')\n", " result = convert_to_int(str)\n", " print('done!')\n", " \n", " return result" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " print(f\"{do_conversion('123') = }\")\n", " print(f\"{do_conversion('hello') = }\")\n", " print(f\"{do_conversion('987') = }\")\n", "except ValueError:\n", " print('ValueError occured!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combining `with` Statements and `try`…`except` Statements " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "open('gradez.txt')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " with open('gradez.txt', 'r') as accounts:\n", " print(f'{\"ID\":<3}{\"Name\":<7}{\"Grade\"}')\n", " for record in accounts: \n", " student_id, name, grade = record.split()\n", " print(f'{student_id:<3}{name:<7}{grade}')\n", "except FileNotFoundError:\n", " print('The file name you specified does not exist')\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Don't Combine `except` and `finally` in the Same `try` Statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Good Python programming practice says to improve readability of your code, you should use two statements:\n", "- A `try` with a `finally` that closes files.\n", "- A separte `try` with `except` clauses to handle errors.\n", "``` Python\n", "try:\n", " outfile = open(filename, 'w')\n", " \n", " try:\n", " # write to the file\n", " finally:\n", " outfile.close()\n", " \n", "except IOError:\n", " # handle the error\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "##########################################################################\n", "# (C) Copyright 2019 by Deitel & Associates, Inc. and #\n", "# Pearson Education, Inc. All Rights Reserved. #\n", "# #\n", "# DISCLAIMER: The authors and publisher of this book have used their #\n", "# best efforts in preparing the book. These efforts include the #\n", "# development, research, and testing of the theories and programs #\n", "# to determine their effectiveness. The authors and publisher make #\n", "# no warranty of any kind, expressed or implied, with regard to these #\n", "# programs or to the documentation contained in these books. The authors #\n", "# and publisher shall not be liable in any event for incidental or #\n", "# consequential damages in connection with, or arising out of, the #\n", "# furnishing, performance, or use of these programs. #\n", "##########################################################################\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Additional material (C) Copyright 2023 by Ronald Mak" ] } ], "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.11.5" } }, "nbformat": 4, "nbformat_minor": 4 }