Very Simple Python 3 Try Except Valueerror Not Tripping

Very Simple Python 3 Try Except Valueerror Not Tripping

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

1 Answer

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.