在python中处理异常 [英] Handling exceptions in python

查看:59
本文介绍了在python中处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理异常的最佳方法是什么.

What the best way of handling exceptions.

class SRException(Exception):
    default_exception = True

    def somefun1(email):
        try:
            user = somefun2(email)
        except Exception, e:
            raise SRException, ("could not find the email", e)

    def somefun2(email):
        try:
            user = User.objects.get(email = email)
        except Exception, e:
            raise SRException, ("could not find the user objecets",e )

所以当发生异常时,我会获得一长串的异常

So when exception happens I get a long list of Exception

UserProfileException('找不到用户或服务对象",UserProfileException('找不到用户',ServicesException('可以找不到服务",doesNotExist('服务匹配查询不存在.',)))))))))

UserProfileException('could not find the user or service objects', UserProfileException('could not find the user', ServicesException('could not find the service', DoesNotExist('Services matching query does not exist.',))))))))

错误和上面的代码示例不相同.但是我想我已经说清楚了.

Error and above code examples are not the same. But I guess I made my point clear.

那么处理异常的最佳方法是什么.我是否应该在所有例外情况中都提出这一点.每当发生异常时,我都会向技术团队发送邮件.

So what the best way of handling exceptions. Should I not raise it in every exceptions. And I am sending mail to technical team every time exceptions occurs.

推荐答案

通常不必在调用堆栈的每个级别都包装异常.您最好在调用堆栈中某个较高的位置捕获异常,并将堆栈跟踪信息转储到技术支持电子邮件中.这将非常清楚地表明问题出在哪里以及从何处被调用.

It is usually not necessary to wrap exceptions at every level of the call stack. You are better off catching exceptions somewhere high up in the call stack and dumping a stack trace into the tech-support email. This will indicate quite clearly where the problem occurred and where it was called from.

sys.exc_info()[2] 中进行一些挖掘,您甚至可以在每个堆栈框架中转储完整的参数和局部变量列表,这将为支持人员提供令人讨厌的电子邮件地址.

With a bit of digging around in sys.exc_info()[2], you could even dump a complete list of parameters and locals in each stack frame, which would give support staff the offending email address.

这篇关于在python中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆