The try
keyword in Python is used in exception handling to test a block of code for errors. If an exception occurs, the control is passed to the corresponding except block, allowing the program to handle errors gracefully and avoid crashes.
Example
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
You can't divide by zero!
Syntax
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Optional: Code to execute if no exception occurs
finally:
# Optional: Code that always executes, regardless of exceptions
Why Use try?
- Error Prevention: Allows you to anticipate and handle potential errors during runtime.
- Graceful Handling: Prevents program crashes by providing alternative actions when an error occurs.
- Maintain Flow: Ensures that the program continues executing even if an exception arises.
- Code Debugging: Identifies where exceptions are likely to occur for better debugging.
Common Examples
1. Basic Try-Except Block
try:
number = int(input("Enter a number: "))
print(f"You entered {number}")
except ValueError:
print("That's not a valid number!")
Input/Output:
Enter a number: hello
That's not a valid number!
2. Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
Input/Output:
Enter a number: 0
Division by zero is not allowed.
3. Using else
try:
num = int(input("Enter a positive number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {num}")
Input/Output:
Enter a positive number: 10
You entered: 10
4. Using finally
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed.")
Output (if the file doesn’t exist):
File not found!
Execution completed.
5. Raising Exceptions in a try Block
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative")
except ValueError as e:
print(f"Error: {e}")
Input/Output:
Enter your age: -5
Error: Age cannot be negative