2

I was taught that an empty except catches all kinds of exceptions, but when I try this block of code it doesn't catch the exception and raise a SyntaxError. What am I doing wrong?

try:
    print "Hello"
except:
    print("Caught!")  #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?

even when I specify the kind of exception as SyntaxErrorit still doesn't catch it.

try:
    print "Hello"
except SyntaxError:
    print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
Ayxan Haqverdili
  • 23,309
  • 5
  • 37
  • 74
  • 1
    Forget about trying to catch that exception and just use `from __future__ import print_function` instead. (See also [What is \_\_future\_\_ in Python used for and how/when to use it, and how it works](//stackoverflow.com/q/7075082)) – Aran-Fey Aug 27 '18 at 19:57
  • Also see https://stackoverflow.com/questions/20816332/can-syntax-errors-be-handled – PM 2Ring Aug 27 '18 at 20:29

1 Answers1

3

No. An empty except catches all types of runtime errors; a syntax error is not a runtime error by definition, because the code can't run at all.

Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842