About Lesson
Try-Except Block
- Definition: The
try
block lets you test a block of code for errors. Theexcept
block 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
finally
block 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