如何确定哪个函数调用在Python中引发异常?

14 投票
4 回答
20222 浏览
提问于 2025-04-15 20:01

我需要找出是谁引发了一个错误,以便更好地处理这个字符串错误,有什么办法吗?

看看我的例子:

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中处理这个问题呢?

4 个回答

1

简单的解决方案是这样的:

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

这样做会让代码更容易读懂和理解。

21

如果你的代码中有完全不同的任务需要执行,具体取决于哪个函数出错了,那么像现有的答案所建议的那样,使用分开的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

撰写回答