Exception Handling in
Programming
Covering Custom Inheritance and
Best Practices
Introduction
• Definition: Exception handling allows a
program to manage error conditions and
recover gracefully.
• Importance: Prevents program crashes and
data loss.
Basic Terms
• • Exception, Error, Bug, Fault
• • Syntax errors vs. runtime errors
Exception Handling Flow
• try, catch (Java/Python: except), finally
• Control flow when an exception occurs
• Java Example:
• try {
• int result = n / m;
• } catch (ArithmeticException e) {
• [Link]("Error: Division by zero");9
• } finally {
• [Link]("Cleanup code here");
• }
• Python Example:
• try:
• result = n / m
• except ZeroDivisionError:
• print("Error: Division by zero")
• finally:
• print("Cleanup code here")
Types of Exceptions
• • Built-in exceptions
• • Checked vs. Unchecked (Java)
• • Custom exceptions
Custom Exception Classes
• Why use custom exceptions? For more
descriptive error management
• Python Example:
• class MyCustomError(Exception):
• pass
• try:
• raise MyCustomError("Something went
Exception Inheritance
• Benefits: Specific error types and more
granular control
• Python Example:
• class BaseCustomException(Exception):
• pass
• class InputError(BaseCustomException):
• pass
Handling Multiple Exception Types
• Multiple catch/except blocks
• Java Example:
• try {
• // risky code
• } catch (IOException e) {
• [Link]("File error");
• } catch (ArithmeticException e) {
• [Link]("Math error");
• }
Exception Chaining
• Wrapping one exception within another for
debugging
• Python Example:
• try:
• open("[Link]")
• except Exception as e:
• raise MyCustomError("Custom error") from
e
Real-life Example: Divide by Zero
(Java)
• int n = 10, m = 0;
• try {
• int ans = n / m;
• [Link]("Answer: " + ans);
• } catch (ArithmeticException e) {
• [Link]("Division by zero");
• }
• Program continues safely after exception.
Best Practices
• • Always catch only expected exceptions
• • Clean up resources using finally
• • Log and propagate exceptions when
necessary
Conclusion & Q/A
• Summary of exception handling importance,
custom exception hierarchy, and robust
coding.
• Any questions?