Python/Exceptions: Difference between revisions
From charlesreid1
(Created page with "Class exceptions: ==Abstract datatype example== The case of exception handling for an abstract data type like a stack is pretty clear-cut: there are two explicit error case...") |
No edit summary |
||
| (2 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
==Abstract exception class== | |||
To raise your own custom Exception type, it's really easy to define a new Exception with a custom name: | |||
<pre> | |||
class MyNewException(Exception): | |||
pass | |||
</pre> | |||
Done. Now we can do <code>raise MyNewException("Oh no!")</code>: | |||
<pre> | <pre> | ||
class | class MyNewException(Exception): | ||
pass | pass | ||
def myfunction(): | |||
raise MyNewException("Oh no!") | |||
def main(): | |||
try: | |||
myfunction() | |||
except MyNewException: | |||
print("Successfully handled MyNewException") | |||
if __name__=="__main__": | |||
main() | |||
</pre> | |||
==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, <code>oInstance</code> is the object instance that we are wrapping) | |||
<pre> | |||
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 | |||
</pre> | </pre> | ||
See [[StacksQueues/Python/ArrayStack#Class_implementation]] | ==Links== | ||
Exceptions are the anti-pattern: https://sobolevn.me/2019/02/python-exceptions-considered-an-antipattern | |||
==Related== | |||
See: [[StacksQueues/Python/ArrayStack#Class_implementation]] | |||
==Flags== | |||
[[Category:CS]] | |||
[[Category:Python]] | |||
[[Category:Exceptions]] | |||
Latest revision as of 17:39, 29 March 2019
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