Exception Handling in Python
1. What are Exceptions?
Exceptions are errors that occur during the execution of a program.
They can be caused by invalid input, division by zero, trying to open a non-existent file, etc.
If not handled, exceptions can crash your program.
2. Types of Errors
Syntax Errors:
• Occur when the rules of Python are not followed.
• Example: Missing colon ':' after an if statement.
• Python won’t run the program until you fix these errors.
Exceptions:
• Occur during runtime, even if the syntax is correct.
• Example: Dividing by zero or trying to access a non-existent file.
3. Common Built-in Exceptions
• ZeroDivisionError: Division by zero.
• ValueError: Invalid value (e.g., converting a string to an integer).
• NameError: Using a variable that is not defined.
• TypeError: Using the wrong data type (e.g., adding a string to an integer).
• IndexError: Accessing an index that doesn’t exist in a list.
• FileNotFoundError: Trying to open a file that doesn’t exist.
4. Handling Exceptions
Use try and except blocks to handle exceptions.
The try block contains the code that might raise an exception.
The except block contains the code to handle the exception.
5. Syntax of try and except
try:
# Code that might raise an exception
except ExceptionName:
# Code to handle the exception
6. Example Programs
Example 1: Handling Division by Zero
try:
numerator = 50
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Example 2: Handling Invalid Input (ValueError)
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except ValueError:
print("Error: Please enter a valid number!")
Example 3: Handling Multiple Exceptions
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid numbers!")
Example 4: Using else with try and except
try:
num = int(input("Enter a number: "))
except ValueError:
print("Error: Please enter a valid number!")
else:
print("You entered:", num)
Example 5: Using finally
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found!")
finally:
print("This will always execute.")
file.close() # Ensure the file is closed
Example 6: Raising Exceptions with raise
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
else:
print("Your age is:", age)
Example 7: Using assert
age = int(input("Enter your age: "))
assert age >= 0, "Age cannot be negative!"
print("Your age is:", age)