问题
I would like to except the error the following code produces, but I don't know how.
from datetime import datetime
try:
date = datetime(2009, 12a, 31)
except:
print "error"
The code above is not printing "error"
. That's what I would like to be able to do.
edit: The reason I would like to check for syntax errors, is because 12a is a command line parameter.
Thanks.
回答1:
command-line "parameters" are strings. if your code is:
datetime(2009, '12a', 31)
it won't produce SyntaxError
. It raises TypeError
.
All command-line parameters are needed to be cleaned up first, before use in your code. for example like this:
month = '12'
try:
month = int(month)
except ValueError:
print('bad argument for month')
raise
else:
if not 1<= month <= 12:
raise ValueError('month should be between 1 to 12')
回答2:
You can't catch syntax errors because the source must be valid before it can be executed. I am not quite sure, why you can't simple fix the syntax error, but if the line with the datetime is generated automatically from user input (?) and you must be able to catch those errors, you might try:
try:
date = eval('datetime(2009, 12a, 31)')
except SyntaxError:
print 'error'
But that's still a horrible solution. Maybe you can tell us why you have to catch such syntax errors.
回答3:
If you want to check command-line parameters, you could also use argparse or optparse, they will handle the syntax check for you.
来源:https://stackoverflow.com/questions/1483343/how-to-except-syntaxerror