How to identify what function call raise an except

2020-06-19 04:58发布

i need to identify who raise an exception to handle better str error, is there a way ?

look at my example:

try:
   os.mkdir('/valid_created_dir')
   os.listdir('/invalid_path')
except OSError, msg:

   # here i want i way to identify who raise the exception
   if is_mkdir_who_raise_an_exception:
      do some things

   if is_listdir_who_raise_an_exception:
      do other things ..

how i can handle this, in python ?

4条回答
干净又极端
2楼-- · 2020-06-19 05:18

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.

查看更多
▲ chillily
3楼-- · 2020-06-19 05:21

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.

查看更多
Juvenile、少年°
4楼-- · 2020-06-19 05:28

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 ..
查看更多
在下西门庆
5楼-- · 2020-06-19 05:34

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.

查看更多
登录 后发表回答