try
Statements¶ZeroDivisionError
s and ValueError
s that arise—in this case, allowing the user to re-enter the input# 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
try
Clause¶try
statements enable exception handlingtry
clause followed by a suite of statements that might raise exceptionsexcept
Clause¶try
clause’s suite may be followed by one or more except
clauses else
Clause¶except
clause, an optional else
clause specifies code that should execute only if the code in the try
suite did not raise exceptionsZeroDivisionError
¶try
suite, it terminates immediatelyexcept
handlers following the try
suite, program control transfers to the first oneexcept
handlers, a process called stack unwinding occurs (discussed later)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.ValueError
¶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.