Loading notes...
Loading notes...
B.Tech • Chapter 7
B.Tech level module on Exception Handling & Logging.
Robust software must anticipate and gracefully recover from failures. Python's try-except-else-finally blocks provide a structured way to handle runtime anomalies.
Advanced Engineering Concepts
Instead of crashing, exceptions allow the program to jump to an error-handling block. The 'finally' block is executed no matter what, making it essential for releasing locks or closing network connections. In enterprise applications, print() is insufficient; the built-in 'logging' module is used to track events, warnings, and critical errors across different severity levels.
Code Implementation
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def divide(a, b):
try:
result = a / b
except ZeroDivisionError as e:
logging.error(f"Attempted to divide by zero: {e}")
return None
except TypeError as e:
logging.critical(f"Invalid data types provided: {e}")
raise
else:
logging.info(f"Division successful: {result}")
return result
finally:
logging.debug("Division operation completed.")
divide(10, 0)