9.8.2 try Statements

  • Can handle exceptions so code can continue processing
  • Following code uses exception handling to catch and handle (i.e., deal with) any ZeroDivisionErrors and ValueErrors that arise—in this case, allowing the user to re-enter the input
In [1]:
# dividebyzero.py
"""Simple exception handling example."""

while True:
    # attempt to convert and divide values
    try:
        number1 = int(input('Enter numerator: '))
        number2 = int(input('Enter denominator: '))
        result = number1 / number2
    except ValueError:  # tried to convert non-numeric value to int
        print('You must enter two integers\n')
    except ZeroDivisionError:  # denominator was 0
        print('Attempted to divide by zero\n')
    else:  # executes only if no exceptions occur
        print(f'{number1:.3f} / {number2:.3f} = {result:.3f}')
        break  # terminate the loop
You must enter two integers

Attempted to divide by zero

100.000 / 7.000 = 14.286

try Clause

  • try statements enable exception handling
  • try clause followed by a suite of statements that might raise exceptions

except Clause

  • try clause’s suite may be followed by one or more except clauses
  • Known as exception handlers
  • Each specifies the type of exception it handles

else Clause

  • After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite did not raise exceptions

Flow of Control for a ZeroDivisionError

  • The point in the program at which an exception occurs is often referred to as the raise point
  • When an exception occurs in a try suite, it terminates immediately
  • If there are any except handlers following the try suite, program control transfers to the first one
  • If there are no except handlers, a process called stack unwinding occurs (discussed later)
  • When an except clause successfully handles the exception, program execution resumes with the finally clause (if there is one), then with the next statement after the try statement.

Flow of Control for a ValueError

Flow of Control for a Successful Division

  • When no exceptions occur in the try suite, program execution resumes with the else clause (if there is one); otherwise, program execution resumes with the next statement after the try statement

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.