0
Why my code is still giving an error after using try and except ?
try: def b(c, d, e="abc", f): print() print(c, d, e, f) b(2, 4, 5, f) except: print("default argument shouldn't be followed by non-default argument")
2 Antworten
+ 1
Shantanu understand that try/except only operates during run time so it can catch only run-time exceptions. What you show is a syntax error, which occurs during parsing/interpretation time.
There is a trick you can use to turn this into a run-time error. That trick is to use eval(). Place the code you want to trap for syntax error into a string, and pass it into eval(). The code will not be parsed until run time. Try/except will trigger a SyntaxError error when eval gets executed.
What I show below also uses a trick using docstrings ("""... """ -- surround your code with three double quotes) to let you define a multi-line string.
try:
eval("""
def b(c, d, e="abc", f):
print()
print(c, d, e, f)
b(2, 4, 5, f)
""")
except:
print("default argument shouldn't be followed by non-default argument")
+ 4
You need to change sequence of parameters
try:
def b(c, d, f ,e="abc"):
print()
print(c, d, e, f)
b(2, 4, 5, f)
except:
print("default argument shouldn't be followed by non-default argument")