Junior
What is exception handling in Python?
sobes.tech AI
Answer from AI
Exception handling in Python is a mechanism for catching and responding to errors or events that disrupt the normal execution of a program.
It uses the try...except...finally block or try...except...else...finally.
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handling a specific exception
print("Error: Division by zero!")
except Exception as e:
# Handling any other exception
print(f"An error occurred: {e}")
else:
# Executes if no exceptions occurred in the try block
print("Operation completed successfully.")
finally:
# Always executes, regardless of exceptions
print("Finally block executed.")
Main components:
try: Block of code where an exception might occur.except: Block of code that executes when a specified type of exception occurs in thetryblock. Multipleexceptblocks can be used for different exception types.else: (Optional) Block of code that executes if no exceptions occur in thetryblock.finally: (Optional) Block of code that always executes, regardless of whether an exception occurred or not. Often used for resource cleanup (e.g., closing files).raise: Keyword for explicitly raising an exception.
def divide(a, b):
if b == 0:
raise ValueError("Divisor cannot be zero")
return a / b
try:
divide(10, 0)
except ValueError as e:
print(f"Handling user-defined exception: {e}")
Advantages:
- Increases program reliability.
- Isolates code that may cause errors.
- Provides cleaner separation of normal execution logic from error handling logic.