try BlockContains the code that might raise an exception.
try:
# Code that might cause an error
risky_operation()
another_risky_step()
# ...
try: Keyword to start the exception handling block.try is executed. If an exception occurs here, Python looks for a matching except block.except Block(s)Catches and handles specific exceptions raised in the try block. You can have multiple except blocks for different exception types.
try:
# Risky code
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# Code to handle ZeroDivisionError
print("Error: Cannot divide by zero!")
except ValueError as e:
# Code to handle ValueError, 'e' holds the exception object
print(f"Value error occurred: {e}")
except Exception:
# Catches any other exception (general handler)
print("An unexpected error occurred.")
except [ExceptionType [as alias]]:: Keyword to catch an exception.
ExceptionType: The specific type of exception to catch (e.g., ValueError, TypeError, FileNotFoundError). If omitted, it catches all exceptions.as alias: An optional variable name to assign the exception object to, allowing you to access details about the error.except block is executed if an exception of that type occurs in the try block.else BlockContains code that is executed only if the try block completes successfully without raising any exceptions.
try:
# Risky code that might succeed
file = open("my_file.txt", "r")
except FileNotFoundError:
print("File not found.")
else:
# Code to run if no exception occurred in try
print("File opened successfully.")
file.close()
else: Keyword for the block that runs on successful try execution.else block must be placed after all except blocks.finally BlockContains code that is always executed, regardless of whether an exception occurred in the try block or was handled by an except block. Often used for cleanup actions.