Is it possible to make python print a specified string if it get an error?
What I mean is, if for example I get an error like
Traceback (most recent call last):
File "score_keeper-test.py", line 106, in <module>
app = program()
File "score_keeper-test.py", line 37, in __init__
self.label1.set_text(team1_name)
TypeError: Gtk.Label.开发者_如何学Cset_text() argument 1 must be string, not None
Is there any way to make python print something like "You MUST enter a name in the TWO boxes" instead of the error above?
The Pythonic idiom is EAFP: easier to ask for forgiveness than permission. In this case:
try:
self.label1.set_text(team1_name)
except TypeError:
print "You MUST enter a name in the TWO boxes"
Note how I explicitly catch TypeError
. This is recommended by PEP 8 -- Style Guide for Python Code (essential reading for any Python programmer):
When catching exceptions, mention specific exceptions whenever possible instead of using a bare
except:
clause.
An alternative (not-recommended) approach would be:
if team1_name:
self.label1.set_text(team1_name)
else:
print "You MUST enter a name in the TWO boxes"
...which is an example of LBYL: Look before you leap. This style can leave your code littered in if
-statements.
if value:
#Do stuff
else:
print "You MUST enter a name in the TWO boxes"
Now, here, if the value
is None
, it will print the string - "You MUST enter a name in the TWO boxes"
精彩评论