1

Is it possible to register custom error handler in python - like http://php.net/set_error_handler in PHP? I would like to trigger errors from anywhere in my code and then have email notifications about that (and logging, and anything else I need I'd implement in handler) - I used such pattern in PHP.

maybe I don't understand python's concept well (since I'm newbie in python). Thanks for help.

Serge
  • 1,947
  • 3
  • 26
  • 48
  • 1
    Have you considered using exception handler for this? http://docs.python.org/tutorial/errors.html#handling-exceptions – Maria Zverina May 17 '12 at 12:42
  • have a look at this - http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python – Neil May 17 '12 at 12:43
  • @Maria Zverina: the goal is to avoid big constructs - just trigger error, and all the rest will be done with my custom handler (send notifications, add logging etc) Seems Neil's advice would be helpfull – Serge May 17 '12 at 12:53
  • 2
    @Alex: I don't think so that is possible in Python. Use exceptions. You can have/define a hierarchy of user-defined exception classes in your application and trigger them. – verisimilitude May 17 '12 at 12:58
  • @verisimilitude: thanks, your answer is exhaustive (guess my question was mostly about python philosophy - how does it recommend resolve such problems) – Serge May 17 '12 at 13:31

1 Answers1

2

Not knowing exactly what error handlers are in PHP I will look at this from a python point of view

In python we have exceptions, they are by name exceptional. We throw exceptions when something goes wrong or we are expecting something else or even we just want to fail. Exceptions can be thrown at any point, and then later caught for example

a = 'int'
b = int(a)

Will throw an exception because you cannot convert 'int' to an int, so now to do this with exception handling

try:
    b = int("int")
except ValueError:
    print "can't do that" 

Now you notice we swallow the exception and carry on execution of the program, this isn't always the best idea, sometimes we might want to raise our own exception and crash

class NotADecimalNumber(Exception): pass
try:
    b = int("a")
except ValueError:
    raise NotADecimalNumber("'a' is not a decimal number idiot.")

Now we get our custom exception with a custom message

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91