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
-
1Please edit your post to include the code so that we can see what you're talking about.user4200092– user42000922015年04月13日 15:54:56 +00:00Commented Apr 13, 2015 at 15:54
2 Answers 2
It is absolutely good practice to catch specific errors. There are two general guidelines for use of try: except::
- Keep the
tryblock as short as possible; and - 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:
Exceptionalready incorporatesValueError; and- You don't actually use
efor 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).
5 Comments
pass then it doesn't really matter, but could you not be doing something more useful?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