For Python 2.6 and later and Python 3.x:
except Exception as e: print(e)
For Python 2.5 and earlier, use:
except Exception,e: print str(e)
Answer from jldupont on Stack OverflowFor Python 2.6 and later and Python 3.x:
except Exception as e: print(e)
For Python 2.5 and earlier, use:
except Exception,e: print str(e)
The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
Try/Except isn't printing my message
python - How do you print an error with Try and Except - Stack Overflow
How to get the error line?
Where to use try/except?
What does it mean by "print an exception" in Python?
Why is printing exceptions crucial?
Some reason I cant get my except print statement to print to terminal. It just keeps asking my original question unless the input matches.
def main(): making_faces()
def making_faces(): while True: try: user_input = input("':)' or ':(' ? ") if user_input == ":)": print("Hello! ๐") break elif user_input == ":(": print("Goodbye. ๐") break except: print("Please enter a valid Emoji")
main()
What the hell is up with Reddit Code formatting. It completely ignores it as code.
Firstly to check what is your error, you can watch into your terminal there will be error's name:
print(5+"5")
>>>
Traceback (most recent call last):
File "c:\Users\USER\Desktop\how_to_use_try_except.py",
line 1, in <module>
print(5+"5")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
and to catch it, you need to copy error's name, and except it
try:
print(5+"5")
except TypeError:
print("You can't add string value to int!")
also you can write
try:
print(5+"5")
except TypeError as e:
print(e)
>>>
unsupported operand type(s) for +: 'int' and 'str'
You can use traceback, more specifically traceback.print_exc(). This prints the full error traceback, rather than just the one line produced from using as in your except block.
I've put an example below using a ValueError.
import traceback
try:
int("s")
except ValueError:
traceback.print_exc()
This produces the same print result as if there was no try-except, the difference being that this solution allows the code to continue running.