3: >>> num2=4
4: >>> zero=0
5: >>> result=num1/num2
6: >>> print (result)
7: 0.75
8: >>> result=num1/zero
9: Traceback (most recent call last):
10: File "<stdin>", line 1, in <module>
11: ZeroDivisionError: division by zero
12: >>>
However, on line 8, when Python attempts to divide 3 by 0 , it throws a runtime error and issues a
traceback message. The traceback message on line 10 in Listing 17.4 shows that the error occurs in
File "
line 11 displays what causes the error exception to occur: ZeroDivisionError. As with the
SyntaxError message, Python gives a little more help by also displaying the message division
by zero.
As you would expect, a traceback message is a little different when it comes to a runtime error in a
script. Listing 17.5 includes code that attempts to divide by zero.
LISTING 17.5 A Runtime Error in a Script
Click here to view code image
1: pi@raspberrypi ~ $ python3 py3prog/my_errors.py
2:
3: The Classic "Divide by Zero" error.
4:
5: Traceback (most recent call last):
6: File "py3prog/my_errors.py", line 33, in <module>
7: main()
8: File "py3prog/my_errors.py", line 29, in main
9: divide_zero ()
10: File "py3prog/my_errors.py", line 23, in divide_zero
11: my_error = num_1 / zero
12: ZeroDivisionError: division by zero
13: pi@raspberrypi ~ $
Remember that a traceback message literally traces back to the original runtime error. Thus, you can
see on lines 6 through 11 of Listing 17.5 that the messages starts at the mainline function, main (lines
6 and 7 of Listing 17.5). It then progresses to the divide_zero function (lines 8 and 9 of Listing
17.5), which is called on line 29 of the script. Finally, it zeros in on the problem (lines 10 through 12
of Listing 17.5). As you can see, the culprit is on line 23 of the script, and it is a “division by zero”
error.
The my_errors.py script is displayed in Listing 17.6. Sure enough, on line 23, you can see the
code that incorrectly divides a number by zero.
LISTING 17.6 The my_errors.py Script
Click here to view code image