Skip to main content

3 docs tagged with "exceptions"

View all tags

Handling Exceptions: The `else` and `finally` Blocks

In the last article, we introduced the try...except block as the fundamental way to handle runtime errors in Python. It allows our programs to react to problems gracefully instead of crashing. However, the story doesn't end there. The full try statement includes two more optional but powerful clauses: else and finally.

Introduction to Exception Handling: `try` and `except` Blocks

Up to this point, our scripts have followed a "happy path." We assume the user will enter the correct type of data, the files we want to read will always exist, and we'll never divide by zero. But in the real world, things go wrong. Network connections fail, files are moved, and users enter invalid input.

Raising Exceptions: The `raise` Keyword

We have learned how to handle exceptions that Python raises automatically, like ValueError or FileNotFoundError. But what if you encounter an error condition in your own code that isn't covered by a built-in exception?