You have to define which type of exception you want to catch. So write except Exception as e: instead of except, e: for a general exception.
Other possibility is to write your whole try/except code this way:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # works on python 3.x
logger.error('Failed to upload to ftp: %s', repr(e))
In older versions of Python 2.x, use except Exception, e instead of except Exception as e:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to %s', FTPADDR)
except Exception, e: # works on python 2.x
logger.error('Failed to upload to ftp: %s', repr(e))
Answer from eumiro on Stack OverflowYou have to define which type of exception you want to catch. So write except Exception as e: instead of except, e: for a general exception.
Other possibility is to write your whole try/except code this way:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # works on python 3.x
logger.error('Failed to upload to ftp: %s', repr(e))
In older versions of Python 2.x, use except Exception, e instead of except Exception as e:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to %s', FTPADDR)
except Exception, e: # works on python 2.x
logger.error('Failed to upload to ftp: %s', repr(e))
The syntax except, e: is no longer supported in python 3. Use the following instead.
try:
do_something()
except BaseException as e:
logger.error('Failed to do something: %s', str(e))
How would I get my error message to print before Python errors?
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
What’s the correct way to print an exception in Python when handling errors? - Ask a Question - TestMu AI (formerly LambdaTest) Community
Try/Except isn't printing my message
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.
traceback.format_exc() will yield more info if that's what you want.
import traceback
def do_stuff():
raise Exception("test exception")
try:
do_stuff()
except Exception:
print(traceback.format_exc())
This outputs:
Traceback (most recent call last):
File "main.py", line 9, in <module>
do_stuff()
File "main.py", line 5, in do_stuff
raise Exception("test exception")
Exception: test exception
Some other answer have already pointed out the traceback module.
Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
...will display the traceback of the last exception:
Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
Producing:
Traceback (most recent call last):
File "t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
Few pitfalls with this though:
From the doc of
sys_info:Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)
but, from the same doc:
Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
... will display:
File "e3.py", line 4, in <module>
raise TypeError("Oups!")