Skip to content Skip to sidebar Skip to footer

How To Except Syntaxerror?

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'

Solution 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')
    raiseelse:
    ifnot1<= month <= 12:
        raise ValueError('month should be between 1 to 12')

Solution 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.

Solution 3:

If you want to check command-line parameters, you could also use argparse or optparse, they will handle the syntax check for you.

Post a Comment for "How To Except Syntaxerror?"