
๐Python Exception Handling
Python Exception Handling: In Python, exceptions are errors that occur during program execution. Proper handling of these exceptions prevents program crashes and ensures smooth operation. This guide explains the key concepts of Python exception handling using try, catch, finally, and raise with examples.
๐What is Exception Handling in Python?
Python Exception Handling: An exception is an error that occurs during program execution. Python automatically generates exceptions when errors are encountered, or you can manually trigger exceptions using the raise statement.
When exceptions are not properly handled, the program may terminate unexpectedly. To prevent this, Python provides structured exception handling.
๐Common Examples of Exceptions in Python
- Division by zero
- Accessing a non-existent file
- Adding incompatible data types
- Accessing an invalid index in a list
- Performing database operations on a disconnected server
- Withdrawing more than the available balance in an ATM
๐Why Use Exception Handling?
- Ensures smooth program execution by managing errors effectively.
- Helps isolate error-handling code from normal program logic.
- Improves code readability and clarity.
- Provides a structured way to handle errors in different program segments.
- Allows the program to continue running even if errors occur.
๐Python Exception Handling Keywords
Python Exception Handling: Python handles exceptions using these keywords:
- try
- catch (except in Python)
- finally
- raise
๐1. Python try Statement
The try block contains the code that may raise an exception. If no exception occurs, the code inside the try block runs normally. If an exception occurs, control transfers to the corresponding except block.
๐Syntax:
python
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
print(“Error: Division by zero is not allowed.”)
๐2. Python except Statement (Equivalent to catch)
The except block is used to catch specific types of exceptions. Multiple except blocks can be used for different exception types.
๐Example:
python
try:
num = int(input(“Enter a number: “))
print(10 / num)
except ZeroDivisionError:
print(“Error: Cannot divide by zero.”)
except ValueError:
print(“Error: Invalid input. Please enter a number.”)
๐3. Python finally Statement
The finally block always executes, regardless of whether an exception occurred. It is often used for cleanup actions.
๐Example:
python
try:
file = open(“example.txt”, “r”)
content = file.read()
print(content)
finally:
file.close() # Ensures the file closes even if an error occurs
print(“File closed successfully.”)
๐4. Python raise Statement
The raise statement is used to trigger an exception manually. It is useful for custom error conditions.
๐Syntax:
python
def check_age(age):
if age < 18:
raise ValueError(“Age must be 18 or above.”)
print(“Access granted.”)
try:
check_age(16)
except ValueError as e:
print(f”Error: {e}”)
๐Important Python Exceptions and Errors
Exception Type | Description |
ArithmeticError | Base class for arithmetic errors like division by zero. |
ImportError | Raised when a module import fails. |
IndexError | Raised when accessing an invalid index in a list. |
KeyError | Occurs when a key is not found in a dictionary. |
NameError | Raised when referencing an undefined variable. |
ValueError | Occurs when a function receives an invalid argument. |
EOFError | Raised when input() reaches end-of-file condition. |
ZeroDivisionError | Raised when dividing by zero. |
IOError | Occurs during input/output operations. |
SyntaxError | Raised for syntax errors in code. |
IndentationError | Raised for incorrect indentation. |
๐Error vs. Exception
Feature | Error | Exception |
Definition | Errors are often serious issues that occur at runtime. | Exceptions are manageable events that can be handled using try-except blocks. |
Recovery | Errors are generally not recoverable. | Exceptions can be handled and resolved. |
Examples | OutOfMemoryError, StackOverflowError. | ValueError, IndexError, ZeroDivisionError. |
๐Summary
- Python Exception Handling ensures smooth program execution by managing errors effectively.
- Key keywords include try, except, finally, and raise.
- Common exceptions like ZeroDivisionError, ValueError, and ImportError are handled efficiently using try-except blocks.
- Using finally ensures code cleanup, while raise allows custom error triggering.