else and finally blocks in try-except statements

PHOTO EMBED

Tue Jun 18 2024 02:48:31 GMT+0000 (Coordinated Universal Time)

Saved by @pynerds #python

#finally block always gets executed
#else block is only executed if no exception was raised

import math

try:
   print("Hello, World!")
   print(10/ 5)
   print(math.sqrt(-9))

except ValueError:
   print("a ValueError has occurred")

except IndexError:
    print("IndexError has occurred")

else:
    print("No Exception was raised.")
finally:
    print("This block always gets executed")
content_copyCOPY

https://www.pynerds.com/exception-handling-in-python/