Some_function()在执行时引发异常,因此程序跳转到异常:

try:
    some_function()
except:
    print("exception happened!")

如何查看导致异常发生的原因?


当前回答

只要避免捕获异常,Python打印的回溯就会告诉你发生了什么异常。

其他回答

你通常不应该用try来捕获所有可能的异常:…除非这太宽泛了。只要抓住那些无论出于什么原因都会发生的事情。如果您真的必须这样做,例如,如果您想在调试时了解有关某个问题的更多信息,那么您应该这样做

try:
    ...
except Exception as ex:
    print ex # do whatever you want for debugging.
    raise    # re-raise exception.

下面是我处理异常的方式。我们的想法是,如果容易的话,尝试解决问题,然后在可能的情况下添加一个更理想的解决方案。不要在生成异常的代码中解决问题,否则代码会失去原始算法的跟踪,而原始算法应该被准确地编写。但是,传递解决问题所需的数据,并返回一个lambda,以防在生成它的代码之外无法解决问题。

path = 'app.p'

def load():
    if os.path.exists(path):
        try:
            with open(path, 'rb') as file:
                data = file.read()
                inst = pickle.load(data)
        except Exception as e:
            inst = solve(e, 'load app data', easy=lambda: App(), path=path)()
    else:
        inst = App()
    inst.loadWidgets()

# e.g. A solver could search for app data if desc='load app data'
def solve(e, during, easy, **kwargs):
    class_name = e.__class__.__name__
    print(class_name + ': ' + str(e))
    print('\t during: ' + during)
    return easy

目前,由于我不想考虑应用程序的用途,所以我没有添加任何复杂的解决方案。但在未来,当我了解更多可能的解决方案时(因为应用程序设计得更多),我可以添加一个以during为索引的解决方案字典。

在这个例子中,一种解决方案可能是寻找存储在其他地方的应用程序数据,比如‘app.p’文件被错误删除了。

现在,因为编写异常处理程序不是一个明智的想法(我们还不知道解决它的最佳方法,因为应用程序的设计将不断发展),我们只是返回简单的修复,这就像我们第一次运行应用程序一样(在这种情况下)。

为了补充Lauritz的答案,我创建了一个用于异常处理的装饰器/包装器,并且包装器记录发生了哪种类型的异常。

class general_function_handler(object):
    def __init__(self, func):
        self.func = func
    def __get__(self, obj, type=None):
        return self.__class__(self.func.__get__(obj, type))
    def __call__(self, *args, **kwargs):
        try:
            retval = self.func(*args, **kwargs)
        except Exception, e :
            logging.warning('Exception in %s' % self.func)
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(e).__name__, e.args)
            logging.exception(message)
            sys.exit(1) # exit on all exceptions for now
        return retval

这可以在类方法或带有装饰器的独立函数上调用:

@general_function_handler

完整的例子请参阅我的博客:http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/

在Python 2中,以下代码很有用

except Exception, exc:

    # This is how you get the type
    excType = exc.__class__.__name__

    # Here we are printing out information about the Exception
    print 'exception type', excType
    print 'exception msg', str(exc)

    # It's easy to reraise an exception with more information added to it
    msg = 'there was a problem with someFunction'
    raise Exception(msg + 'because of %s: %s' % (excType, exc))

使用类型class和as语句

try:#code
except Exception as e:
     m=type(e)
     #m is the class of the exception
     strm=str(m)
     #strm is the string of m