Python/Exceptions
From charlesreid1
Abstract exception class
To raise your own custom Exception type, it's really easy to define a new Exception with a custom name:
class MyNewException(Exception): pass
Done. Now we can do raise MyNewException("Oh no!")
:
class MyNewException(Exception): pass def myfunction(): raise MyNewException("Oh no!") def main(): try: myfunction() except MyNewException: print("Successfully handled MyNewException") if __name__=="__main__": main()
Exception Handling
This is a useful pattern for exception handling: if you need to use a try/except block, and you want to have a block that's run if the exception does NOT occur, you can add an "else" to the block.
For example, if we are writing a method for one class that is wrapping an instance of another class, we can transparently provide access to the instance's attributes with the following:
(here, oInstance
is the object instance that we are wrapping)
class Wrapper(object): def __getattribute__(self,s): """ If an attribute of Wrapper is accessed, call this. Try to get the attribute from Wrapper, and if that fails, try to get it from oInstance. Also, detect if it is an instance method, just to show off. """ try: x = super(Wrapper,self).__getattribute__(s) except AttributeError: pass else: # Here is the "else" in a try/except block return x # We only get here if we encountered the exception x = self.oInstance.__getattribute__(s) # Before we return: detect if this is an instance method if type(x)==type(self.__init): print("Congratulations, you have a method") # Okay on with the show return x
Links
Exceptions are the anti-pattern: https://sobolevn.me/2019/02/python-exceptions-considered-an-antipattern
Related
See: StacksQueues/Python/ArrayStack#Class_implementation