Definition of Exception Handling:
Exception Handling in Python is the process of responding to unwanted or unexpected events (called exceptions) that occur while the program is running.
Exceptions can crash the program if not handled. Python provides a way to gracefully handle errors using the try
, except
, else
, and finally
blocks.
🔹 Syntax of Try-Except Block:
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
🔹 Common Exceptions in Python:
ZeroDivisionError
: Raised when a number is divided by zero.ValueError
: Raised when an operation receives an inappropriate value.TypeError
: Raised when an operation is performed on an incompatible data type.IndexError
: Raised when accessing an invalid index in a list or string.FileNotFoundError
: Raised when a file is not found.
Handling Divide by Zero Exception Example:
def divide(a, b):
try:
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
# Function calls
divide(10, 2) # Valid division
divide(5, 0) # Will raise ZeroDivisionError
Output:
Result: 5.0
Error: Division by zero is not allowed.
Raising Custom Exceptions:
You can use the raise
keyword to throw custom exceptions:
raise Exception("This is a custom error.")
Exception handling allows you to manage runtime errors and prevent program crashes. It improves robustness, user-friendliness, and error tracking in Python programs.