我需要确定谁提出异常来处理更好的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 ..
Run Code Online (Sandbox Code Playgroud)
我怎么能在python中处理这个?
Ale*_*lli 12
如果您有完全独立的任务要执行,具体取决于哪个函数失败,正如您的代码似乎显示的那样,那么单独的try/exec块(如现有答案所示)可能更好(尽管您可能需要跳过第二部分,如果第一个失败了).
如果你在任何一种情况下都需要做很多事情,并且只有少量工作取决于哪个功能失败,那么分离可能会产生大量的重复和重复,因此你建议的形式可能更好.在这种情况下,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
Run Code Online (Sandbox Code Playgroud)
当然,而不是print你将使用if检查来确定要做什么处理.
单独包装"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
Run Code Online (Sandbox Code Playgroud)
无论如何,这将有助于提高可读性/理解力.