Exception Handling – Advanced You’ve already seen basic blocks in Python, similar to in JavaScript. Now let’s go deeper into advanced exception handling so you can write more robust, production-ready code . Exceptions Multiple Exception Types In Python, you can catch different exceptions with separate blocks. JS equivalent: Catching Multiple Exceptions in One Line The Clause runs only if no exception occurs . The Clause always runs — useful for cleanup (like closing files or DB connections). Raising Exceptions You can raise your own exceptions with . JS equivalent: Custom Exception Classes Custom exceptions let you express domain-specific errors clearly (e.g., “Out of stock” vs a generic ). They also let you catch exactly what you mean , without swallowing other bugs. How to define one Always inherit from (not ). is for system-level events like or . Usage: Catching: Add fields for programmatic handling Custom attributes let you handle errors by data , not by parsing messages. Use a base exception for your package/module Create a small hierarchy so callers can: catch specific errors when needed, or catch all your domain errors with one base class. Chaining exceptions ( ) Preserve the root cause (e.g., parsing/IO) while giving a domain error: This keeps a clean domain message and the original traceback. When to create a custom exception (vs built-ins) Use built-ins when they already match: Bad type → Bad value → Missing key → Division by zero → Create a custom exception when: You need domain meaning (e.g., ). Callers should catch your errors as a group (via your base class). You need extra fields (e.g., , ) for handling or logging. Practical tips Name with suffix: , . Inherit from your own base ( ) for easy grouping. Store context on the exception (attributes). Don’t catch broadly unless you re-raise or log; prefer specific classes. Organize : put them in inside your package for reuse. Example: small hierarchy in inventory Why custom over general? Clarity : communicates intent to readers and logs. Precision : catch only what you can safely handle. Testability : assert specific exceptions in unit tests. Extensibility : add fields for richer error handling without brittle string parsing. ✅ Why it matters : Advanced exception handling ensures your program doesn’t crash unexpectedly . By raising and catching custom errors , you make debugging and error messages much clearer. and give you fine-grained control over execution flow, similar to but more structured than JavaScript.