Handling an Exception
try: a = 2 b = 0 print( a/b ) print(" Done with division...") except ZeroDivisionError: print (" A ZeroDivisionError exception happened...") finally: print("This line will run no matter what")
The final block will be handled no matter whether an exception will be handled or not
Handling of multiple exception types
try: var = 10 print(var + " hi") print(var / 2) except ZeroDivisionError: print("Division by zero") except(ValueError, TypeError): print("Houston we have a problem...")
Catch all errors
try: text = ("This is a string") print(word / 0) except: print("An exception happened")
Raise an exception on your own
print("Get ready!") raise ValueError print("No one executed me...")
Re-raise an exception
try: number = 7 / 0 except: print("Houston we have a problem...") raise
- Printer-friendly version
- Log in to post comments
- 114 views