如何在Python中识别什么函数调用引发异常?

2024-05-13 08:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要确定是谁引发异常来处理更好的str错误,有办法吗?

看看我的例子:

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

我怎么能用python处理这个问题呢?


Tags: anifisos错误exceptiondo例子
3条回答

简单的解决方案如何:

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

如果您有完全独立的任务要执行,这取决于哪个函数失败,如您的代码所示,那么正如现有的答案所建议的那样,独立的try/exec块可能更好(尽管如果第一个部分失败,您可能需要跳过第二个部分)。

如果在这两种情况下都有许多事情需要做,并且只有少量的工作取决于哪个函数失败,那么分离可能会产生大量重复和重复,因此您建议的形式可能会更好。在这种情况下,Python标准库中的traceback模块可以提供帮助:

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

当然,您将使用if检查来确定要执行的处理,而不是print

单独包装“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 

无论如何,这将有助于阅读/理解。

相关问题 更多 >