Skip to main content
Errors in Python come in two main types: syntax errors and exceptions. This guide shows you how to handle them properly.

Syntax Errors

Syntax errors (parsing errors) occur when Python can’t understand your code:
The parser shows the offending line and points to the error location with arrows. In this case, the error is at print() because a colon (:) is missing.

Exceptions

Even syntactically correct code can cause errors during execution:
The last line shows the exception type (ZeroDivisionError, NameError, TypeError) and a description of what went wrong.

Handling Exceptions

Use try...except to handle exceptions:
How it works:
  1. The try clause is executed
  2. If no exception occurs, the except clause is skipped
  3. If an exception occurs, the rest of the try clause is skipped
  4. If the exception matches the type in except, that clause is executed
  5. If the exception doesn’t match, it’s passed to outer try statements

Multiple Except Clauses

Handle different exceptions differently:

Exception Hierarchy

Exceptions inherit from base classes:
Output: B, C, D
Order matters! If you reversed the except clauses (with except B first), it would print B, B, B.

Accessing Exception Details

The else Clause

Code in the else 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

Use raise to trigger an exception:
Shorthand for exception classes:
Re-raising exceptions:

Exception Chaining

When handling an exception, you can raise another exception and preserve the context:
Explicit chaining:
Disable chaining:

User-defined Exceptions

Create custom exceptions by deriving from Exception:
Most exceptions are named with names ending in “Error”, similar to standard exceptions.

Defining Clean-up Actions

The finally clause always executes, whether an exception occurred or not:
Complex example:
The finally clause is useful for releasing external resources (files, network connections) regardless of whether the operation was successful.

Predefined Clean-up Actions

The with statement ensures objects are properly cleaned up:
The file is always closed after the block, even if an error occurs.

Exception Groups

Raise multiple unrelated exceptions together:

Handling Exception Groups

Use except* to handle specific exception types in a group:

Enriching Exceptions with Notes

Add contextual information to exceptions:
Practical example:

Best Practices

Be Specific

Catch specific exceptions rather than using bare except:

Use finally

Clean up resources in finally clauses or use with statements

Document Exceptions

Document which exceptions your functions might raise

Don't Silence Errors

Avoid empty except blocks that hide problems

Next Steps

You now understand how to handle errors gracefully. Finally, learn about Classes to create your own custom types and objects.