key components of exception handling
Generic Exception Handling vs. Handling Specific Exceptions
try:
risky_operation()
except IndexError: # Handle specific exception types first.
handle_index_error()
except Exception as e: # More general exception must come last.
handle_generic_error()
finally:
cleanup()Raising Exceptions
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Divisor cannot be zero")
return a / b
try:
result = divide(4, 0)
except ZeroDivisionError as e:
print(e)def some_risky_operation():
if condition:
raise Exception("Some generic error occurred")Using “with” for Resource Management
File is automatically closed when the block is exited
with open("example.txt", "r") as file:
data = file.read()Callback Function: ExceptionHook
Python 3 introduced the better handling of uncaught exceptions by providing an optional function for printing stack traces. The sys.excepthook can be set to match any exception in the module as long as it has a hook attribute.
# test.py
import sys
def excepthook(type, value, traceback):
print("Unhandled exception:", type, value)
# Call the default exception hook
sys.\_\_excepthook\_\_(type, value, traceback)
sys.excepthook = excepthook
def test_exception_hook():
throw_some_exception()How to silence exceptions?
try:
risky_operation()
except SomeSpecificException:
passfor item in my_list:
try:
perform_something(item)
except ExceptionType:
continuetry:
some_function()
except SpecificException:
handle_specific_exception()
else:
no_exception_raised()