Python - 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]:
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
In [14]:
try:
img2 = ImageryObject("user\img\file2.img")
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
In [15]:
try:
img2 = ImageryObject()
img2.display()
except:
print("something bad happened")
else:
print("else block")
finally:
print("finally block")
In [21]:
try:
img2 = ImageryObject()
img2.display()
except Exception as ex:
print("something bad happened")
print("exactly what whent bad? : " + str(ex))
In [22]:
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))
In [ ]: