DEV Community


Posted on

Python: a simple Try/Catch can change the experience

You don't come to Python for the complexity. Indeed, its beauty is in the simplicity and the tons of free libraries you can easily import in your scripts.

However, it's usually a good idea to handle errors, especially the unexpected ones.

Why handling errors?

Such topic is quite tricky, as it's easy to mislead someone with personal opinions, so let's try to keep it factual here.

It could be quite annoying to get 50 lines of raw errors in the terminal because an "unknown exception" happened.

As a developer, it means you did not anticipate that scenario. In the end, it's not that bad, and you actually don't have to handle every possible errors in the Universe in your script.

However, a simple try/catch or similar structures (e.g., those with the else keyword or finally) can give the right information quickly in one line to your users.

How to handle errors in Python

    # ...code
except Exception as e:
    print("Exception encountered:", e)
Enter fullscreen mode Exit fullscreen mode

Of course, the above try/catch is very basic. Python Linters (static analysis) would likely flag it, as the exception is too generic here and the variable names are too short.

However, that's pretty much how it works in Python. To do it more accurately, please read this documentation.

A few practical situations

I like to include the KeyboardInterrupt exception in my scripts to prevent ugly displays in case the user decides to interrupt the execution for whatever reason.

If your script deals with online resources or APIs, checking for timeouts or network errors is a good approach.

Other common cases can be import errors and bad/missing inputs.

Wrap up

Catching errors and returning a well-formed message can save a lot of time to your users and prevent any misunderstanding.

Top comments (0)