How to exclude SyntaxError?
I would like to rule out 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 above code doesn't print "error"
. This is what I would like to do.
edit: The reason I want to check for syntax errors is because 12a is a command line parameter.
Thank.
source to share
command line options are command line strings. if your code is:
datetime(2009, '12a', 31)
it will not produce SyntaxError
. He picks up TypeError
.
All command line parameters must first be cleared before being used in your code. eg:
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')
source to share
You cannot catch syntax errors because the source must be valid before it can be executed. I'm not really sure why you can't just fix the syntax error, but if a string with datetime is generated automatically from user input (?) And you should catch those errors, you can try:
try:
date = eval('datetime(2009, 12a, 31)')
except SyntaxError:
print 'error'
But this is still a terrible decision. Perhaps you can tell us why you should catch syntax errors like this.
source to share