Syntax Errors
Syntax errors (parsing errors) occur when Python can’t understand your code:print() because a colon (:) is missing.
Exceptions
Even syntactically correct code can cause errors during execution:ZeroDivisionError, NameError, TypeError) and a description of what went wrong.
Handling Exceptions
Usetry...except to handle exceptions:
- The
tryclause is executed - If no exception occurs, the
exceptclause is skipped - If an exception occurs, the rest of the
tryclause is skipped - If the exception matches the type in
except, that clause is executed - If the exception doesn’t match, it’s passed to outer
trystatements
Multiple Except Clauses
Handle different exceptions differently:Exception Hierarchy
Exceptions inherit from base classes:B, C, D
Accessing Exception Details
The else Clause
Code in theelse clause runs if no exception occurs:
The
else clause is better than adding code to the try clause because it avoids catching exceptions that weren’t raised by the protected code.Raising Exceptions
Useraise to trigger an exception:
Exception Chaining
When handling an exception, you can raise another exception and preserve the context:User-defined Exceptions
Create custom exceptions by deriving fromException:
Defining Clean-up Actions
Thefinally clause always executes, whether an exception occurred or not:
The
finally clause is useful for releasing external resources (files, network connections) regardless of whether the operation was successful.Predefined Clean-up Actions
Thewith statement ensures objects are properly cleaned up:
Exception Groups
Raise multiple unrelated exceptions together:Handling Exception Groups
Useexcept* to handle specific exception types in a group:
Enriching Exceptions with Notes
Add contextual information to exceptions:Best Practices
Be Specific
Catch specific exceptions rather than using bare
except:Use finally
Clean up resources in
finally clauses or use with statementsDocument Exceptions
Document which exceptions your functions might raise
Don't Silence Errors
Avoid empty
except blocks that hide problems