Try-Except Block
- Definition: The
tryblock lets you test a block of code for errors. Theexceptblock lets you handle the error. - Syntax: python
try: # code that may raise an exception except ExceptionType: # code to handle the exception - Example: python
try: print(10 / 0) except ZeroDivisionError: print("Cannot divide by zero") # Output: Cannot divide by zero
Finally Block
- Definition: The
finallyblock lets you execute code, regardless of whether an exception was raised or not. - Syntax: python
try: # code that may raise an exception except ExceptionType: # code to handle the exception finally: # code that will always execute - Example: python
try: print(10 / 0) except ZeroDivisionError: print("Cannot divide by zero") finally: print("This will always execute") # Output: This will always execute