0

trying to get my try except block to work.

import sys

def main():
    try:
        test = int("hello")
    except ValueError:
        print("test")
        raise

main()

output is

C:\Python33>python.exe test.py
test
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    main()
  File "test.py", line 5, in main
    test = int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

C:\Python33>

would like the except to trip

2
  • This is expected as you are raising the exception using raise Commented Feb 27, 2014 at 20:54
  • You should read the documentation for raise. The first sentence states: If no expressions are present, raise re-raises the last exception that was active in the current scope. Commented Feb 27, 2014 at 20:58

1 Answer 1

6

You are reraising the exception. It's working as designed.

The test is printed right at the top there before the traceback, but you used raise so the exception still is causing a traceback:

>>> def main():
...     try:
...         test = int("hello")
...     except ValueError:
...         print("test")
...         raise
... 
>>> main()
test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in main
ValueError: invalid literal for int() with base 10: 'hello'

Remove the raise and just the test print remains:

>>> def main():
...     try:
...         test = int("hello")
...     except ValueError:
...         print("test")
... 
>>> main()
test
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.