How to identify what function call raise an exception in Python?

How about the simple solution:

try:
   os.mkdir('/valid_created_dir')
except OSError, msg:
   # it_is_mkdir_whow_raise_ane_xception:
   do some things

try:
   os.listdir('/invalid_path')
except OSError, msg:    
   # it_is_listdir_who_raise_ane_xception:
   do other things ..

Wrap in "try/catch" each function individually.

try:
   os.mkdir('/valid_created_dir')
except Exception,e:
   ## doing something,
   ## quite probably skipping the next try statement

try:
   os.listdir('/invalid_path')
except OSError, msg:
   ## do something 

This will help readability/comprehension anyways.


If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed).

If you have many things that you need to do in either case, and only a little amount of work that depends on which function failed, then separating might create a lot of duplication and repetition so the form you suggested may well be preferable. The traceback module in Python's standard library can help in this case:

import os, sys, traceback

try:
   os.mkdir('/valid_created_dir')
   os.listdir('/invalid_path')
except OSError, msg:
   tb = sys.exc_info()[-1]
   stk = traceback.extract_tb(tb, 1)
   fname = stk[0][2]
   print 'The failing function was', fname

Of course instead of the print you'll use if checks to decide exactly what processing to do.


Here's the clean approach: attach additional information to the exception where it happens, and then use it in a unified place:

import os, sys
def func():
    try:
       os.mkdir('/dir')
    except OSError, e:
        if e.errno != os.errno.EEXIST:
            e.action = "creating directory"
            raise

    try:
        os.listdir('/invalid_path')
    except OSError, e:
        e.action = "reading directory"
        raise

try:
    func()
except Exception, e:
    if getattr(e, "action", None):
        text = "Error %s: %s" % (e.action, e)
    else:
        text = str(e)
    sys.exit(text)

In practice, you'd want to create wrappers for functions like mkdir and listdir if you want to do this, rather than scattering small try/except blocks all over your code.

Normally, I don't find this level of detail in error messages so important (the Python message is usually plenty), but this is a clean way to do it.