DEV Community

Cover image for Tip: Avoid using bare except in Python
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

4 1

Tip: Avoid using bare except in Python

In Python, keyboard interrupts and system exits are propagated using exceptions (i.e. KeyboardInterrupt and SystemExit). As a result, a bare except clause is going to catch something like the user hitting Ctrl + C.

Consider the following code. If the user were to try exiting the program, the keyboard interrupt would be caught by the except clause. This would be undesirable, as it prevents the user from actually exiting the program until they provide valid input.

while True:
  try:
    s = input('Input a number:')
    x = int(s)
  except:
    print('Not a number, try again!')
Enter fullscreen mode Exit fullscreen mode

A way to prevent this would be to use Exception which will ensure that the user will not be trapped. The only problem with this approach is that Exception is generic and will handle pretty much anything thrown at it.

while True:
  try:
    s = input('Input a number:')
    x = int(s)
  except Exception:
    print('Not a number, try again!')
Enter fullscreen mode Exit fullscreen mode

The correct way to handle errors is to specify the type of error you expect. For example, in this code sample, ValueError would be appropriate.

while True:
  try:
    s = input('Input a number:')
    x = int(s)
  except ValueError:
    print('Not a number, try again!')
Enter fullscreen mode Exit fullscreen mode

As a rule of thumb, you should only handle expected failure states using except with an appropriate error type. In the case of unexpected errors, it might be better to simply let the program fail naturally and exit.


Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay