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

22nd Sep 2018, 4:05 PM
Roger Wang
Roger Wang - avatar
8 Réponses
22nd Sep 2018, 5:44 PM
Anna
Anna - avatar
+ 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
22nd Sep 2018, 4:11 PM
Roger Wang
Roger Wang - avatar
+ 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.
26th Sep 2021, 3:06 AM
Ruchit Prajapati
Ruchit Prajapati - avatar
+ 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')
16th Jan 2022, 2:49 PM
Ruchit Prajapati
Ruchit Prajapati - avatar
+ 1
Iam interesting with this Thanks for note
14th Aug 2021, 9:38 PM
‎محمد يسن عمر‎
‎محمد يسن عمر‎ - avatar
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.
27th Sep 2021, 2:09 PM
Siriki Lohit
Siriki Lohit - avatar
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
3rd Oct 2022, 2:22 PM
Bhavya Shree
Bhavya Shree - avatar