-3

I have this little piece of code I wrote that isn't excepting the errors that could be thrown at it. Here's the code:

def println(stringint):
    try:
        print stringint
    except (SyntaxError, NameError):
        print "Invalid format."

I run the code from the python interpreter like this, and only like this:

>>> import pcl
>>> pcl.println("Hello")

Why aren't the errors being excepted? How can I catch the errors?

Vladimir Putin
  • 661
  • 1
  • 8
  • 18

2 Answers2

3

Those errors that has to do with syntax are parse level errors, which means, that are errors that take place before that particular code being interpreted.

The following aren´t the same type of errors:

print("Hello)  # Note the missing '"'

that

print(4/0)     # Syntactically correct, but obviously an error.

Hence, syntax error can't be handled by the try -- except block.

See this answer for more detail: SyntaxError inconsistency in Python?

Community
  • 1
  • 1
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

Your code works fine, "Hello" should raise neither an EOLError nor a NameError, because the quotes are closed, and it is a string.

soniaup
  • 53
  • 8
  • Well, I put NameError in the just in case the user enters something like `pcl.println(hello)`. – Vladimir Putin Jun 30 '14 at 15:24
  • 1
    @SomeGuy Then NameError will be raised outside of your function call. – Kos Jun 30 '14 at 15:26
  • Function arguments are evaluated before the function is called. You can't catch `pcl.println(hello)` from *inside* `pcl.println()` because `pcl.println()` is never called (assuming there is no variable in scope named `hello`). – kindall Jun 30 '14 at 15:26
  • @SomeGuy What do you mean by "the user enters something like `pcl.println(hello)`"? The "user" is the person who is using the code. *You* are the person who is doing the programming, and doing the calls. If you are trying to use exceptions to help you catch errors in your program, that's not the right model. – Andrew Jaffe Jun 30 '14 at 15:36