why Try block is retuning SyntaxError before executing except block in Python3?

Viewed 38

Here I am trying to print "Invalid text" when the string contains Backslash " \ ". I know that in Python strings, the backslash " \ " is a special character called the "escape" character. But when python tries to read the variable s, it returns SyntaxError.

try:
     s = '\'
except:
    print("Invalid text")

output is

File "C:\Users\Admin\PycharmProjects\pythonProject19\main.py", line 4
    raise SyntaxError if s = '\':
                              ^
SyntaxError: unterminated string literal (detected at line 4)
2 Answers

You have an unterminated string literal.The proper way to terminate a string literal as is described by you in this instance is s == '\\'.

Related