How to determine which function call throws an exception in Python?

I need to determine who throws an exception to handle the best str error, is there any 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 can i handle this in python?

+3
source share
4 answers

If you have completely separate tasks to perform depending on which function worked, as your code shows, then separate try / exec blocks, as existing answers suggest, may be better (although you probably might need to skip the second if the first of them failed).

, , , - , , , , , traceback Python :

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

, print if, , .

+8

"try/catch" .

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 

/.

+8

:

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 ..
+1

: , , :

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 need to create wrappers for functions like mkdir and listdir if you want to do this, instead of scattering small try / except blocks throughout your code.

As a rule, I do not consider this level of detail in error messages so important (Python messages are usually many), but this is a clean way to do this.

0
source

Source: https://habr.com/ru/post/1735429/


All Articles