Exception Handling in Python – Notes
1. What is an Exception?
An exception is an error that occurs during the execution of a program and stops it unless handled.
Common Exceptions:
• ZeroDivisionError
• ValueError
• TypeError
• FileNotFoundError
2. Why Use Exception Handling?
To prevent the program from crashing and provide a meaningful message to the user.
3. try–except Block
Use try-except when you think a block of code may raise an error.
Example:
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
4. try–except–else
The else block runs only if no exception occurs.
Example:
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", num)
5. try–except–finally
The finally block runs whether or not an exception occurs. Useful for cleanup.
Example:
try:
f = open("[Link]")
except FileNotFoundError:
print("File not found!")
finally:
print("Task completed.")
6. Raising Exceptions
You can raise your own exceptions using raise.
Example:
age = -1
if age < 0:
raise ValueError("Age cannot be negative")
7. Creating Custom Exceptions
You can define custom exception classes.
Example:
class MyError(Exception):
pass
try:
raise MyError("Custom error occurred")
except MyError as e:
print(e)
Summary:
• Use try–except to handle errors gracefully.
• else runs if no error.
• finally always runs.
• raise is used to trigger errors manually.