The try statement in Python is used to handle exceptions, allowing you to catch and respond to errors that occur during the execution of a program. It works with except, else, and finally blocks to provide a robust error-handling mechanism.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: Cannot divide by zero!
try:
result = int("abc")
except ValueError:
print("Invalid input! Cannot convert to integer.")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: Invalid input! Cannot convert to integer.
The else
block is executed if the code block inside the try
block does not raise any exceptions.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
# Output: Division successful: 5.0
The finally
block is executed after the try
block and any except
block.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
if 'file' in locals() and not file.closed:
file.close()
print("File operation complete.")
# Output (if file does not exist): File not found!
# Output (always): File operation complete.
The else
block is executed if the code block inside the try
block does not raise any exceptions. The finally
block is executed after the try
block and any except
block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
finally:
print("End of try-except block.")
# Output: Division successful: 5.0
# Output: End of try-except block.