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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like