Exception handling in Python refers to the process of responding to the occurrence of exceptions—errors detected during execution.
- Python provides mechanisms like try, except, finally, and raise to handle exceptions gracefully.
- It helps in preventing program crashes and allows programs to handle error conditions more effectively.
Q.) What is the Use of Exception Handling in Python?
- It is used to gracefully manage and respond to errors that occur during the execution of a program, without crashing the program. It helps to detect runtime errors and take corrective action.
1.) try Block:
The try block is used to wrap code that might generate an exception.
- If an error occurs within the try block, the flow of control immediately moves to the except block.
Example: If the input cannot be converted to an integer (e.g., input is “abc”), an exception will be thrown and caught in the except block.
try:
num = int(input("Enter a number: "))
print("You entered:", num)2.) except Block:
The except block contains the code that runs if an exception is raised in the try block.
- It can handle specific exception types.
Example:
try:
value = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")3.) finally Block:
The finally block will execute no matter what — whether or not an exception is raised.
- It’s typically used for cleanup tasks like closing files or database connections.
Example:
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file...")
file.close() # This will run whether or not an exception occurred4.) raise Statement:
The raise statement is used to manually trigger an exception in a program.
- It is helpful for enforcing constraints or signaling unexpected conditions.
Example:
def divide(a, b):
if b = = 0:
raise ZeroDivisionError("You cannot divide by zero.")
return a / b
try:
print(divide(10, 0))
except ZeroDivisionError as e:
print("Caught an exception:", e)