What is an Exception?
An exception is like a sudden roadblock in your Python program. If something unexpected happens (like dividing by zero or accessing an undefined variable), Python throws an exception and stops the program—unless you handle it!
Common Python Exceptions
Exception | When it Happens |
---|---|
SyntaxError |
When Python doesn't understand your code (e.g., missing : ) |
NameError |
When you use a variable that hasn’t been defined |
TypeError |
When you mix incompatible types (e.g., adding int and str ) |
ValueError |
When a function gets an argument of the right type but wrong value |
IndexError |
When trying to access a list index that doesn’t exist |
KeyError |
When accessing a nonexistent dictionary key |
ZeroDivisionError |
When you try to divide by zero (which breaks math!) |
FileNotFoundError |
When you try to open a file that doesn’t exist |
Examples of Common Exceptions
SyntaxError
– The Grammar Police
print("Hello Python!" # Oops! Missing closing parenthesis
NameError
– Who’s That?
print(hello_world) # Variable hello_world is not defined!
TypeError
– Mixing Apples and Oranges
print("Age: " + 25) # Can't concatenate string and integer!
IndexError
– Out of Bounds
numbers = [1, 2, 3]
print(numbers[5]) # No item at index 5!
KeyError
– Missing Keys
dictionary = {"name": "Alice"}
print(dictionary["age"]) # No 'age' key in dictionary!
Handling Exceptions with try-except
To prevent program crashes, use try-except
!
try:
print(10 / 0) # ZeroDivisionError!
except ZeroDivisionError:
print("You can’t divide by zero!")
Summary
Python has many built-in exceptions, and handling them properly makes your programs more robust!
- Learn common exceptions (e.g.,
TypeError
,ValueError
,IndexError
) - Use
try-except
to handle errors gracefully - Debug smarter and keep your program running smoothly!
0 Comments