Exception Handling in Python is a mechanism used to handle runtime errors, ensuring that the program's flow is not interrupted even when an unexpected event occurs. It allows you to "catch" errors and handle them gracefully rather than letting the program crash.
An Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. While Syntax Errors (like missing a colon) prevent code from running at all, Exceptions occur when syntactically correct code encounters an error during execution (e.g., trying to open a file that doesn't exist).
The core of exception handling involves four keywords:
try: This block contains the code that might throw an error.
except: This block contains the code that executes if an error occurs in the try block.
else: (Optional) Code here runs only if no exceptions were raised in the try block.
finally: (Optional) Code here runs no matter what, regardless of whether an exception occurred. This is perfect for closing files or database connections.
FileNotFoundError: Raised when a file or directory is requested but doesn't exist.
ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.
ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
TypeError: Raised when an operation is applied to an object of an inappropriate type.
This example prevents a crash when a user tries to divide by zero or enters non-numeric data.
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Error: You cannot divide by zero!") except ValueError: print("Error: Please enter a valid integer.") except Exception as e: print(f"An unexpected error occurred: {e}") else: print(f"Success! The result is {result}") finally: print("Execution complete.")
This is a standard practice to ensure files are handled safely.
try: with open("config_data.txt", "r") as file: data = file.read() except FileNotFoundError: print("Error: The file 'config_data.txt' was not found.") except PermissionError: print("Error: You do not have permission to read this file.")
You can manually trigger an exception using the raise keyword if a specific condition is met.
def check_age(age): if age < 0: raise ValueError("Age cannot be negative!") return f"Age is {age}" try: print(check_age(-5)) except ValueError as error: print(error)
| Benefit | Description |
| Robustness | Prevents the application from crashing in front of the user. |
| Clean Code | Separates error-handling logic from the main functional code. |
| Debugging | Provides specific error messages that help developers find issues faster. |
| Resource Safety | Ensures files and network connections are closed using the finally block. |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION