Exceptions
Python supports (and extensively uses) exception handling as a means of testing for error conditions and other "exceptional" events in a program. Indeed, it is even possible to trap the exception caused by a syntax error.
Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.
Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply-nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.
Exceptions are often used as an alternative to the if
-block, especially in threaded situations. A commonly-invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission," which is attributed to Grace Hopper In this first code sample, there is an explicit check for the attribute (i.e., "asks permission"):
This second sample follows the EAFP paradigm:
try: ham = spam.eggs except AttributeError: handle_errorThese two code samples have the same effect, although there will be performance differences. When spam
has the attribute eggs
, the EAFP sample will run faster. When spam
does not have the attribute eggs
(the "exceptional" case), the EAFP sample will run slower. The Python profiler can be used in specific cases to determine performance characteristics. If exceptional cases are rare, then the EAFP version will have superior average performance than the alternative. In addition, it avoids the whole class of time-of-check-to-time-of-use (TOCTTOU) vulnerabilities, other race conditions, and is compatible with duck typing. A drawback of EAFP is that it can be used only with statements; an exception cannot be caught in a generator expression, list comprehension, or lambda function.
Read more about this topic: Python Syntax And Semantics
Famous quotes containing the word exceptions:
“For true poetry, complete poetry, consists in the harmony of contraries. Hence, it is time to say aloudand it is here above all that exceptions prove the rulethat everything that exists in nature exists in art.”
—Victor Hugo (18021885)
“Skepticism is unbelief in cause and effect. A man does not see, that, as he eats, so he thinks: as he deals, so he is, and so he appears; he does not see that his son is the son of his thoughts and of his actions; that fortunes are not exceptions but fruits; that relation and connection are not somewhere and sometimes, but everywhere and always; no miscellany, no exemption, no anomaly,but method, and an even web; and what comes out, that was put in.”
—Ralph Waldo Emerson (18031882)
“Every declaration of love contains an unstated list of exceptions and demands.”
—Mason Cooley (b. 1927)