Exceptions Aren’t Exceptional
Explore how to use exceptions in Python not just for errors but as a flow control mechanism. Learn the EAFP approach, see practical examples with inventory management, and understand why exceptions can simplify program logic and improve code maintainability.
We'll cover the following...
Novice programmers tend to think of exceptions as only useful for exceptional circumstances. However, the definition of exceptional circumstances can be vague and subject to interpretation. Consider the following two functions:
These two functions behave identically. If divisor is zero, an error message is printed; otherwise, a message printing the result of the division is displayed.
We could avoid ZeroDivisionError ever being thrown by testing for it with
an if statement. In this example, the test for a valid division is relatively simple-looking (divisor == 0). In some cases, it can be rather ...