Errors are an inevitable part of programming. Python provides multiple ways to handle and debug errors efficiently. Understanding errors and exceptions is crucial for writing robust programs.
1. Types of Errors in Python
Python errors can be classified into two main types:
1.1 Syntax Errors
These occur when Python cannot interpret the code due to incorrect syntax.
Example:
print("Hello" # Missing closing parenthesis
Error Output:
SyntaxError: unexpected EOF while parsing
1.2 Runtime Errors (Exceptions)
These occur during program execution and can cause the program to crash.
Example:
x = 10 / 0 # Division by zero
Error Output:
ZeroDivisionError: division by zero
Some common exceptions include:
ZeroDivisionError
: Dividing by zeroNameError
: Using an undefined variableTypeError
: Mismatched data typesIndexError
: Accessing an invalid list indexKeyError
: Accessing a missing key in a dictionaryValueError
: Invalid value in type conversion
2. Exception Handling with try-except
Python allows handling errors using the try-except
block.
Basic Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Cannot divide by zero!
Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
Catching All Exceptions
try:
print(1 / 0)
except Exception as e:
print("An error occurred:", e)
3. Using finally and else Blocks
finally
Block: Always executes, whether an exception occurs or not.else
Block: Executes only if no exception occurs.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print("Result:", result)
finally:
print("Execution completed.")
4. Raising Custom Exceptions
Python allows raising custom exceptions using the raise
keyword.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18!")
return "Access granted"
try:
print(check_age(16))
except ValueError as e:
print("Error:", e)
Output:
Error: Age must be at least 18!
Summary
✅ Syntax errors occur due to incorrect code structure.
✅ Runtime errors (exceptions) occur during execution.
✅ Use try-except
to handle exceptions and prevent program crashes.
✅ The finally
block ensures cleanup tasks always run.
✅ Use raise
for custom exceptions when needed.