Exception Handling in Python
Exception handling in Python is a way to handle errors or exceptions that occur during program
execution, preventing the program from crashing. It allows developers to handle unexpected
situations gracefully using try, except, else, and finally blocks.
Basic Syntax of Exception Handling:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("No errors occurred.")
finally:
print("Execution completed.")
Handling ZeroDivisionError
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
Handling ValueError
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter an integer.")
Handling Multiple Exceptions
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)
Using finally Block
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file (if opened).")
Why Use Exception Handling?
1. Prevents program crashes due to runtime errors.
2. Improves user experience by providing meaningful error messages.
3. Ensures important cleanup actions (e.g., closing files, releasing resources).
4. Makes debugging easier by identifying specific errors.