简体   繁体   中英

Handling exceptions in 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('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.

Your exception handler is too broad, catch only the specific exceptions you know you can handle . There is no sense in catching an Exception only to wrap it in another exception and re-raising it; an exception object carries a Traceback that will show you what path the code is going. Just let the Exception bubble up, and catch it at a level where you can recover from the exception.

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.

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.

First of all, never just check for Exception ! Always use the correct subtype you are actually expecting.

Also you shouldn't encapsulate already useful exceptions into other ones; and in general use the type of the exception as an identification of what happens. Then you can simply keep throwing (informative) exceptions at low level, and catch them all separately at a higher level to determine the correct error message for the end user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM