Before learning to handle errors, we must understand what they are and why they occur.
What is an Error?
An error is an issue in your program that prevents Python from executing it correctly. Errors can occur due to mistakes in the code, invalid operations, or unexpected situations during program execution.
Types of Errors
Python broadly classifies errors into two categories:
1. Syntax Errors
These happen when you write code that violates Python’s grammar rules. The program won’t even start until the syntax is corrected.
# Example: Syntax Error
if True
print("Hello")
# ❌ Missing colon after if statement
Python will raise:
SyntaxError: expected ':'
2. Exceptions (Runtime Errors)
These occur while the program is running, even though the syntax is correct. Examples include dividing by zero or accessing a variable that doesn’t exist.
# Example: Runtime Error
x = 10 / 0
Python will raise:
ZeroDivisionError: division by zero
Common Built-in Exceptions
Some of the most frequently encountered exceptions are:
NameError– using a variable that hasn’t been definedTypeError– applying an operation to the wrong type (e.g., adding string + int)ValueError– passing an invalid value (e.g., converting "abc" to int)IndexError– accessing a list index that doesn’t existKeyError– accessing a dictionary key that doesn’t existZeroDivisionError– dividing by zero
# Example of a NameError
print(my_var) # ❌ my_var is not defined
NameError: name 'my_var' is not defined
Why Errors are Useful
Errors might seem frustrating, but they are Python’s way of telling you:
- What went wrong
- Where the issue occurred
- How to fix it (in many cases)
Understanding error messages is the first step toward becoming a confident programmer.
Key Takeaways
- Syntax Errors happen before the program runs.
- Exceptions happen during program execution.
- Different exceptions provide useful clues about the issue.
No comments:
Post a Comment