Pradyot
Pradyot

Reputation: 3059

Python all encompassing exception

I am looking at code in python that has a try: except Exception block. I have indentified the code that could potentially raise a ValueError.

My question: Does it make sense (or is a good practice) to include the ValueError in the except clause (in addition to the Exception which already encompasses ValueError)?

try:
    func_raises_value_error()
    func_raises_unknown_error()
except (ValueError, Exception) as e:
  pass

Upvotes: 0

Views: 233

Answers (2)

davidedb
davidedb

Reputation: 876

A good habit when dealing with multiple exceptions which can occur in a block of code is to process them from the most specific one to the most general one. As an example, your code could be written as:

try:
    func_raises_value_error()
    func_raises_unknown_error()
except ValueError as e:
  print 'Invalid value specified: %s' % e
except Exception as e:
  print 'A totally unexpected exception occurred: %s' % e

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122061

It is absolutely good practice to catch specific errors. There are two general guidelines for use of try: except::

  1. Keep the try block as short as possible; and
  2. Be as specific as possible about which errors you want to handle.

So rather than e.g.

try:
    print("Please enter your name")
    name = input(" > ")
    print("Please enter your age")
    age = int(input(" > "))
    print("{} is {} years old".format(name, age))
except Exception:
    print("Something went wrong")

you should have:

print("Please enter your name")
name = input(" > ")
print("Please enter your age")

try:
    age = int(input(" > "))
except ValueError:
    print("That's not a number")
else:
    print("{} is {} years old".format(name, age))

Note that this has allowed a much more specific error message, and allowed any errors that weren't anticipated to pass up to the caller (per the Zen of Python: "Errors should never pass silently. Unless explicitly silenced.")


In your specific case, there is no point to using except (ValueError, Exception) as e:, for two reasons:

  1. Exception already incorporates ValueError; and
  2. You don't actually use e for anything.

If there is nothing you can (or want to) do about the errors raised by either function, you might as well just use except Exception: (which is better than a bare except:, at least).

Upvotes: 5

Related Questions