This program prompts the user to input a first_number 1 and, if the
user does not enter q to quit, a second_number 2. We then divide these two
numbers to get an answer 3. This program does nothing to handle errors,
so asking it to divide by zero causes it to crash:
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
Traceback (most recent call last):
File "division_calculator.py", line 11, in <module>
answer = int(first_number) / int(second_number)
~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
ZeroDivisionError: division by zero
It’s bad that the program crashed, but it’s also not a good idea to let
users see tracebacks. Nontechnical users will be confused by them, and in
a malicious setting, attackers will learn more than you want them to. For
example, they’ll know the name of your program file, and they’ll see a part
of your code that isn’t working properly. A skilled attacker can sometimes
use this information to determine which kind of attacks to use against
your code.
The else Block
We can make this program more error resistant by wrapping the line that
might produce errors in a try- except block. The error occurs on the line
that performs the division, so that’s where we’ll put the try- except block.
This example also includes an else block. Any code that depends on the try
block executing successfully goes in the else block:
--snip--
while True:
--snip--
if second_number == 'q':
break
1 try:
answer = int(first_number) / int(second_number)
2 except ZeroDivisionError:
print("You can't divide by 0!")
3 else:
print(answer)
We ask Python to try to complete the division operation in a try block 1,
which includes only the code that might cause an error. Any code that
depends on the try block succeeding is added to the else block. In this case,
if the division operation is successful, we use the else block to print the
result 3.
The except block tells Python how to respond when a ZeroDivisionError
arises 2. If the try block doesn’t succeed because of a division-by-zero error,
194 Chapter 10