Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Exception Handling & Exception Classes: Complete OOP Guide with Examples

Exception and Exception Classes in Python (Object-Oriented Programming)

In real-world programming, errors are unavoidable. Python provides a powerful mechanism called exception handling to manage errors gracefully without stopping the program.

In this tutorial, you will learn how exceptions work, how to handle them, and how to create custom exception classes using Object-Oriented Programming.


1. What is an Exception?

An exception is an error that occurs during program execution.

Instead of crashing the program, Python allows us to handle these errors using special blocks.


Example of an Exception

x = 10
y = 0

print(x / y)

Output:

ZeroDivisionError

2. Why Use Exception Handling?

Exception handling helps to:

  • Prevent program crashes
  • Improve user experience
  • Handle unexpected situations
  • Maintain program flow
  • Debug errors efficiently

3. Try-Except Block

Python uses try and except to handle exceptions.


Basic Example

try:
x = 10
y = 0
print(x / y)

except ZeroDivisionError:
print("Cannot divide by zero")

4. Multiple Exceptions

You can handle multiple errors.

try:
x = int("abc")

except ValueError:
print("Invalid value")

except ZeroDivisionError:
print("Division error")

5. Finally Block

The finally block always executes.

try:
print("Processing...")
x = 10 / 2

except ZeroDivisionError:
print("Error occurred")

finally:
print("Execution completed")

6. Else Block

Runs only if no exception occurs.

try:
x = 10 / 2

except ZeroDivisionError:
print("Error")

else:
print("No error occurred")

7. What are Exception Classes?

In Python, every exception is an object of a class.

All exceptions inherit from a base class called:

BaseException

Most exceptions come from:

Exception

8. Built-in Exception Classes

ExceptionDescription
ValueErrorInvalid value
TypeErrorWrong data type
ZeroDivisionErrorDivision by zero
IndexErrorInvalid index
KeyErrorMissing dictionary key

9. Creating Custom Exception Classes

You can create your own exceptions using OOP.


Example: Custom Exception

class AgeError(Exception):
pass

Using Custom Exception

def check_age(age):
if age < 18:
raise AgeError("Age must be 18 or above")
print("Valid age")

try:
check_age(15)

except AgeError as e:
print(e)

10. Exception Class Hierarchy

BaseException

Exception

ValueError, TypeError, ZeroDivisionError

11. Raising Exceptions

You can manually trigger errors using raise.


Example

def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b

print(divide(10, 2))

12. Real-World Example

Bank System with Exception Handling

class InsufficientBalance(Exception):
pass

class BankAccount:

def __init__(self, balance):
self.balance = balance

def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalance("Not enough balance")
self.balance -= amount
return self.balance

account = BankAccount(1000)

try:
account.withdraw(1500)

except InsufficientBalance as e:
print(e)

13. Why Use Custom Exceptions?

Custom exceptions help to:

  • Make code more readable
  • Handle specific errors
  • Improve debugging
  • Build professional applications

14. Best Practices

✔ Use specific exception types
✔ Avoid catching all exceptions blindly
✔ Always log errors when needed
✔ Use custom exceptions for business logic
✔ Keep error messages clear and meaningful


15. Common Mistakes

❌ Using bare except

except:
pass

✔ Avoid this — it hides errors


❌ Ignoring exceptions

✔ Always handle or log them properly


❌ Overusing custom exceptions

✔ Use only when necessary


Conclusion

Exception handling and exception classes are essential parts of Python Object-Oriented Programming. They help you manage errors gracefully, build robust applications, and create custom error-handling logic tailored to your program.

By mastering exceptions, you can write safer, more reliable, and professional Python code.




Post a Comment

0 Comments