0

Not showing a syntax error which i have raised as an exception in except block as to show a syntax error, its catcing the double bracket invalid syntax error and displaying invalid syntax.

 try:
     k=open('C:\\Users\\admin\\Desktop\\lol.txt'))
     k.write("Helo World")
 except SyntaxError:
     print("There is a Syntax error")
 except OSError:
     print("The Error has OS Issues")
 finally:
     print("The Error has been specified above")
Harshal SG
  • 403
  • 3
  • 7

1 Answers1

1

Syntax errors are thrown when the code is compiled, and a complete module is compiled before any of it executes. So well before it gets anywhere near actually executing your try:...except block.

If you want to handle a Syntax error put the code in a separate module and wrap the try block around the import statement:

try:
   import hello
except SyntaxError:
    print('There is a syntax error')

and then separately in hello.py:

k=open('C:\\Users\\admin\\Desktop\\lol.txt'))
k.write("Helo World")

Now you'll get the expected output There is a syntax error

Duncan
  • 92,073
  • 11
  • 122
  • 156