Python try statement
Created By: chatGPT
Python provides a way to handle exceptions using the
try
statement, which allows you to write code that can throw exceptions while also enabling you to manage those exceptions gracefully. The general structure includes a try
block and one or more except
blocks to catch and handle exceptions. It can also include finally
to execute code regardless of whether an exception occurred. Here’s an example:try:
# Attempt to divide by zero
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful, result is:", result)
finally:
print("Execution completed.")
In this example, the code inside the
try
block attempts to divide a number by zero, which generates a ZeroDivisionError
. The except
block catches the exception and prints a friendly message. The optional else
block will execute if no exceptions occur, while finally
will always execute, ensuring any necessary cleanup.try:
# Read a file
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
else:
print("File content:", content)
finally:
print("File operation completed.")
You can also handle multiple exceptions simultaneously by specifying them in a tuple in the
except
clause. This is useful when you want to handle different types of errors in a similar way.try:
# Convert user input to an integer
num = int(input("Enter a number: "))
except (ValueError, TypeError):
print("Invalid input! Please enter a valid number.")
else:
print("You entered:", num)
finally:
print("Input operation completed.")