How to except SyntaxError?

爱⌒轻易说出口 提交于 2021-01-27 20:07:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!