python exception message capturing
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Python Exception Message Capturing
00:30 Accepted Answer Score 1234
01:05 Answer 2 Score 393
01:18 Answer 3 Score 55
01:49 Answer 4 Score 69
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/4690...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #exception #logging #except
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Python Exception Message Capturing
00:30 Accepted Answer Score 1234
01:05 Answer 2 Score 393
01:18 Answer 3 Score 55
01:49 Answer 4 Score 69
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/4690...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #exception #logging #except
#avk47
ACCEPTED ANSWER
Score 1234
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 2
Score 393
The syntax is no longer supported in python 3. Use the following instead.
try:
do_something()
except BaseException as e:
logger.error('Failed to do something: ' + str(e))
ANSWER 3
Score 69
There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)
try:
...
except Exception as e:
print(e.message)
ANSWER 4
Score 55
Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.
import logging
logger = logging.Logger('catch_all')
def catchEverythingInLog():
try:
... do something ...
except Exception as e:
logger.error(e, exc_info=True)
... exception handling ...
This is now the old way (though still works):
import sys, traceback
def catchEverything():
try:
... some operation(s) ...
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
... exception handling ...
exc_value is the error message.