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
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
How would I get my error message to print before Python errors?
Try/Except isn't printing my message
How to get the error line?
What does it mean by "print an exception" in Python?
Why is printing exceptions crucial?
I am trying to make a pay calculator to calculate overtime, and my calculator is set up like this:
https://hastebin.com/wehuroruzi.py
From line 14 to 19 I state that If the 'pay_rate' input from the user isn't an integer or float point, then send an error message saying that the user must supply a number.
My issue is that Python gives me an error before the message can be sent to the user. The error being that whatever string that the user sent has no definition in the code.
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.
I've been dealing with legacy code that uses Try Excepts. The issue I'm having is that when a failure occurs the stack trace points to the line the Except is on (well the line below that's reporting it).
Code looks a little like this:
try:
...
except Exception as e:
print(f"Error {str(repr(e))}")Is this legacy code written incorrectly? Is there a reason we don't want to stack trace?
Maybe I'm wrong and this is returning the stacktrace but in a file that I'm not looking at, but I wanted to double check because so far Excepts seem to be a hidderance for me when I'm troubleshooting.