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
21 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