San Jose State University Department of Applied Data Science
**DATA 200 Computational Programming for Data Analytics**
Spring 2023 Instructor: Ron Mak
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9.8.2 `try` Statements"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We can write our own exception handlers with Python's `try` statement. The following code repeately prompts the user for two numbers to divide until the user enters two valid numbers\n",
"- The `try` statement enables exception handling. Its suite contains statements that _might_ raise exceptions.\n",
"- Each `except` clause introduces a suite to handle a particular type of exception.\n",
"- The optional `else` clause introduces a suite to execute if the try suite did _not_ raise any exceptions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# dividebyzero.py\n",
"\"\"\"Simple exception handling example.\"\"\"\n",
"\n",
"while True:\n",
" # attempt to convert and divide values\n",
" try:\n",
" number1 = int(input('Enter numerator: '))\n",
" number2 = int(input('Enter denominator: '))\n",
" result = number1 / number2\n",
" except ValueError: # tried to convert non-numeric value to int\n",
" print('You must enter two integers\\n')\n",
" except ZeroDivisionError: # denominator was 0\n",
" print('Attempted to divide by zero\\n')\n",
" else: # executes only if no exceptions occur\n",
" print(f'{number1:.3f} / {number2:.3f} = {result:.3f}')\n",
" break # terminate the loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Flow of control in a `try` statement"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### If the `try` suite does not raise any exceptions, the suite executes normally and the `except` clauses are skipped. Since there is an `else` clause in the example, its suite executes to print the results and break the loop.\n",
"#### If the user enters an invalid value for either of the two `input()` function calls, the `try` suite immediately leaves and the `ValueError` exeption handler executes. If the division attempts to divide by zero, the `try` suite immediately leaves and the `ZeroDivisionError` exeption handler executes. In either exception case, the `else` clause (if there is one) is skipped. In the example, the loop goes around again to reprompt the user for two values."
]
},
{
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}