+ 12
Can Try-Except blocks ever handle Syntax Errors? (Python, but you can also explain what happens in other languages also)
I’ve never seen it happen before and I’m curious if Syntax Errors can be caught.
8 odpowiedzi
+ 10
I currently don’t think it’s possible because as interpreter parses the source code, it won’t understand what to translate the code in the Try block to.
EDIT: Thank you Maninder Singh and Anna for showing exceptions that catch the SyntaxError exception. :)
try:
$$
except:
print(01)
Output:
SyntaxError
+ 3
Yes, when pointing the exception block to the error type simply point it to handle Syntax errors this will work with syntax errors executed within the try block like having an invalid argument with exec() but hard-coded syntax errors like print()) will still stop the script in runtime unfortunately.
+ 3
a = 'print('
b = '"Hello)"'
try:
exec(a+b) #this will try to execute print("Hello)" <= note the wrong syntax
except SyntaxError:
print('Well that didn\'t work')
+ 1
Iam interesting with this
Thanks for note
0
In most of the cases, it will be able to handle syntax errors. It's very rare, that it MIGHT not be able to cope with SyntaxError. or you may use like
try:
some_statements
except SyntaxError:
some
I didn't try this yet, but I will tell the feedback of this.
Hope this helps.
0
a = 'print('
b = '"Hello)"'
try:
exec(a+b) #this will try to execute print("Hello)" <= note the wrong syntax
except SyntaxError:
print('Well that didn\'t work')
Can someone explain this, why exec(a+b) is syntax error