try:
print("Syntax Error) # Ending quote omitted
except SyntaxError:
print("Syntax Error")
SyntaxError: EOL while scanning string literal
Right after the 1st print statement
system is generating error message. How can we make it to use our except statement?
Thank U.
look at your code.
what are you telling it to print?
try it this way:
>>> try:
... print("--syntax error")
... except SyntaxError:
... print("ex syntax error")
...
--syntax error
>>>
Sir,
I want to parse the 1st print statement which has wrong syntax. Then it should go to the exception print message. But my code does not go beyond 1st print statement. Once it parses the 1st print statement the system is generating the error message.
But I want to print my own error message. How do we do that?
Thank U.
You will only execute the exception if there is an error.
You don't actually have a syntax error, the print statement is making you think so, because it prints 'Syntax Error'
it's not simple to capture a syntax error, but it can be done.
This may be of interest to you:
https://airbrake.io/blog/python-exceptio...yntaxerror
Hi Larz60+,
Thanks for the blog link. It is lot of info. Here I trying very simple thing.
try:
print("Syntax Error) # Ending quote omitted
except SyntaxError:
print("Syntax Error")
I want to parse the 1st print statement which has wrong syntax. Then it should go to the exception print message. But my code does not go beyond 1st print statement. Once it parses the 1st print statement the system is generating the error message.
But I want to print my own error message. How do we do that?
Thank U.
Why do you want to do that?
Hi ndc85430,
If this works
x = [1]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
then why this does not work?
try:
print("Syntax Error) # Ending quote omitted
except SyntaxError:
print("Syntax Error")
Because the interpreter checks that the syntax is valid before executing your code? It won't even allow you to catch the
SyntaxError
.
Still, you haven't answered the question: why do you want to do that? This sounds like the
XY problem.
Hi ndc85430,
I am a self learner. As part of the exercises at the end of the topic this question was given. That is all. I did not know this "XY problem" theory before. Thanks I learned a new thing.
Thanks again.