Search code examples
pythonexceptioncustom-exceptions

Python magic method to alter the way raising an object is handled


I was wondering, is there a simple magic method in python that allows customization of the behaviour of an exception-derived object when it is raised? I'm looking for something like __raise__ if that exists. If no such magic methods exist, is there any way I could do something like the following (it's just an example to prove my point):

class SpecialException(Exception):
    def __raise__(self):
        print('Error!')

raise SpecialException() #this is the part of the code that must stay

Is it possible?


Solution

  • I don't know about such magic method but even if it existed it is just some piece of code that gets executed before actually raising the exception object. Assuming that its a good practice to raise exception objects that are instantiated in-place you can put such code into the __init__ of the exception. Another workaround: instead of raising your exception directly you call an error handling method/function that executes special code and then finally raises an exception.