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.

5
  • 1
    Have you considered using exception handler for this? docs.python.org/tutorial/errors.html#handling-exceptions Commented May 17, 2012 at 12:42
  • have a look at this - stackoverflow.com/questions/1319615/… Commented May 17, 2012 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 Commented May 17, 2012 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. Commented May 17, 2012 at 12:58
  • @verisimilitude: thanks, your answer is exhaustive (guess my question was mostly about python philosophy - how does it recommend resolve such problems) Commented May 17, 2012 at 13:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

s/is not a number/is not a decimal number/ :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.