Python/Exceptions: Difference between revisions
From charlesreid1
No edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
Class exceptions: | Class exceptions: | ||
==Abstract | ==Abstract exception class== | ||
To raise your own custom Exception type, it's really easy to define a new Exception with a custom name: | |||
<pre> | <pre> | ||
class | class MyNewException(Exception): | ||
pass | pass | ||
</pre> | </pre> | ||
Done. Now we can do <code>raise | Done. Now we can do <code>raise MyNewException("Oh no!")</code>: | ||
<pre> | |||
class MyNewException(Exception): | |||
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> | |||
==Related== | |||
See: [[StacksQueues/Python/ArrayStack#Class_implementation]] | |||
==Flags== | |||
[[Category:CS]] | [[Category:CS]] | ||
[[Category:Python]] | [[Category:Python]] | ||
[[Category:Exceptions]] | [[Category:Exceptions]] | ||
Revision as of 15:32, 11 September 2018
Class exceptions:
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
Related
See: StacksQueues/Python/ArrayStack#Class_implementation