10.3. Detecting and Handling Exceptions

Exceptions can be detected by incorporating them as part of a try statement. Any code suite of a try statement will be monitored for exceptions.

There are two main forms of the try statement: try-except and try-finally. These statements are mutually exclusive, meaning that you pick only one of them. A try statement is either accompanied by one or more except clauses or exactly one finally clause. (There is no such thing as a hybrid “try-except-finally.”)

try-except statements allow one to detect and handle exceptions. There is even an optional else clause for situations where code needs to run only when no exceptions are detected. Meanwhile, try-finally statements allow only for detection and processing ...

Get Core Python Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.