The Python Oracle

python exception message capturing

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Question
00:46 Accepted answer (Score 1105)
01:39 Answer 2 (Score 366)
01:57 Answer 3 (Score 88)
03:09 Answer 4 (Score 59)
03:31 Thank you

--

Full question
https://stackoverflow.com/questions/4690...

Answer 2 links:
[sys.exc_info()]: https://docs.python.org/3.6/library/sys....
[traceback documentation]: https://docs.python.org/3.6/library/trac...

--

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.