Exception handling
Exception handling¶
Exceptions are classes. You can define your own by inheriting from Exception
class.
try:
statements
except Exception_type1 as e1:
handling statements
except Exception_type2 as e2:
specific handling statements
except Exception as generic_ex:
generic handling statements
else:
some more statements # executes if no exceptions were fired
finally:
default statements which will always be executed # put logic such as conn close / mem release statements here
In [13]:
Copied!
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
image is displayed
In [14]:
Copied!
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
image is displayed else block finally block
In [15]:
Copied!
try:
img2 = ImageryObject()
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
try:
img2 = ImageryObject()
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
something bad happened finally block
In [21]:
Copied!
try:
img2 = ImageryObject()
img2.display()
except Exception as ex:
print("something bad happened")
print("exactly what whent bad? : " + str(ex))
try:
img2 = ImageryObject()
img2.display()
except Exception as ex:
print("something bad happened")
print("exactly what whent bad? : " + str(ex))
something bad happened exactly what whent bad? : __init__() missing 1 required positional argument: 'file_path'
In [22]:
Copied!
try:
img2 = ImageryObject('path')
img2.dddisplay()
except TypeError as terr:
print("looks like you forgot a parameter")
except Exception as ex:
print("nope, it went worng here: " + str(ex))
try:
img2 = ImageryObject('path')
img2.dddisplay()
except TypeError as terr:
print("looks like you forgot a parameter")
except Exception as ex:
print("nope, it went worng here: " + str(ex))
nope, it went worng here: 'ImageryObject' object has no attribute 'dddisplay'
In [ ]:
Copied!