1

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.

poke
  • 369,085
  • 72
  • 557
  • 602
laspal
  • 13
  • 2
  • First, what do you want to do ? Your code makes no sense, therefor if you want us to give you an anwser, provides you goal so we can understand the problem. – Bite code Dec 13 '10 at 13:40

3 Answers3

4

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.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
2

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

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.

poke
  • 369,085
  • 72
  • 557
  • 602
  • In Python, we `raise` exceptions; we don't `throw` them ;-) – Chris Morgan Dec 13 '10 at 11:32
  • @Chris Morgan: Yeah, I know, but it's still the same thing :P Apart from that, this answer applies to all languages that have exceptions anyway.. – poke Dec 13 '10 at 11:33