Exception Handling in Python - Comprehensive Notes
What is Exception Handling?
Exception handling is a mechanism to handle runtime errors in Python.
Ensures that a program runs smoothly by managing errors without abrupt
termination.
Examples of runtime errors:
- Division by zero
- Accessing an invalid index in a list
- Using incorrect data types
Why is Exception Handling Important?
1. Prevents program crashes.
2. Helps provide user-friendly error messages.
3. Improves program reliability and robustness.
4. Allows the program to recover from errors gracefully.
Types of Errors in Python
1. Syntax Errors:
- Occur when Python cannot interpret the code due to incorrect syntax.
- Example:
print("Hello world" # Missing closing parenthesis
2. Exceptions (Runtime Errors):
- Occur during program execution.
- Example:
num = int("abc") # Raises ValueError
Common Exceptions in Python
ZeroDivisionError: Raised when dividing a number by zero.
ValueError: Raised when an operation receives invalid data.
IndexError: Raised when accessing an index out of range.
KeyError: Raised when a dictionary key does not exist.
TypeError: Raised when performing operations on incompatible types.
FileNotFoundError: Raised when a file is not found.
ImportError: Raised when an import statement fails.
Basic Syntax of Exception Handling
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to execute if no exception occurs (optional)
finally:
# Code that executes regardless of an exception (optional)
Detailed Explanation
1. try Block: Contains the code that might raise an exception.
2. except Block: Handles specific exceptions.
3. else Block: Executes if no exception occurs.
4. finally Block: Always executes, whether or not an exception occurs.
Example Code
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.")
else:
print("No exceptions occurred!")
finally:
print("Execution complete.")
Raising Exceptions
You can raise exceptions manually using the raise keyword.
Example:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
Handling Multiple Exceptions
Use multiple except blocks or a single block with a tuple of exceptions.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
Custom Exceptions
You can define your own exception classes by inheriting from the Exception
class.
Example:
class NegativeValueError(Exception):
pass
num = int(input("Enter a positive number: "))
if num < 0:
raise NegativeValueError("Negative values are not allowed.")
Key Points to Remember
- Use try for risky code and except for handling exceptions.
- Always close resources (like files) in the finally block.
- Avoid catching generic exceptions (except Exception) unless necessary.
- Custom exceptions make error handling more meaningful.
Advantages of Exception Handling
1. Error Recovery: Helps the program recover from unexpected situations.
2. Improved Debugging: Makes debugging easier by isolating error-handling
code.
3. User-Friendly Programs: Provides meaningful error messages to users.