Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 53
Exceptions
ОглавлениеExceptions occur during Python code execution when you attempt an action that is not possible or not allowed. Figure 2.8 illustrates an example of Python code that results in an exception. Figure 2.9 has the output that corresponds to the execution of the code in Figure 2.8. Due to the fact that the print function was “Print” and not “print,” a NameError exception occurs. The Python interpreter reports that the “name ‘Print’ is not defined,” or in other words, there is no function with that name. Python programmers encounter this type of exception frequently due to Python’s case sensitivity (discussed in Chapter 1).
Figure 2.8 Python Code with Exception
Description
Figure 2.9 Output for Python Code with Exception
Figure 2.10 illustrates another Python code example that results in a different type of exception. Figure 2.11 has the output that corresponds to the execution of the code in Figure 2.10. The exception that occurs is a TypeError exception, which occurs because line 3 of the Python code in Figure 2.10 attempted to add an integer valued variable and a string valued variable together. The Python interpreter reports which line (line 3) was involved and prints out that line in the error message “result = first_number + second_number.” In addition, the explanation is “unsupported operand type(s) for +: ‘int’ and ‘str.’” It has been our experience that beginning Python programmers find these error messages puzzling (and sometimes frustrating), but as they learn the needed terminology and gain experience, the error messages become more helpful and resolving the issues becomes much easier.
Figure 2.10 Python Code with TypeError Exception
Description
Figure 2.11 Output for Python Code with TypeError Exception
Table 2.5 identifies some common Python built-in exceptions. We will see examples of these and other exceptions later in the book. Chapter 5 has an example that uses an installed package to show a variety of exceptions that can occur (and how to resolve them) as Python programs become more involved. References for other Python built-in exceptions are in the official Python documentation (Python Software Foundation, 2019, “Built-in Exceptions”).
Table 2.5