Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #14

Exception Handling in Python

What Is an Exception?

An exception is an error that occurs during program execution and, if unhandled, crashes your program. Python provides try/except blocks to handle these errors gracefully instead of letting the program stop.

print(10 / 0)   # ❌ ZeroDivisionError: division by zero — program crashes

Basic try / except

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

Catching Multiple Exceptions

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")

Catching Any Exception

try:
    risky_code()
except Exception as e:
    print("Something went wrong:", e)

Tip: catching the generic Exception is fine for logging, but prefer catching specific exceptions whenever you know what could go wrong.

else and finally

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error occurred")
else:
    print("No errors — result is", result)   # runs only if no exception
finally:
    print("This always runs")                  # runs no matter what

Raising Your Own Exceptions

def enroll(age):
    if age < 16:
        raise ValueError("Minimum enrollment age is 16")
    print("Enrollment successful!")

try:
    enroll(12)
except ValueError as e:
    print("Enrollment failed:", e)

Common Built-in Exceptions

ExceptionWhen It Occurs
ValueErrorInvalid value, e.g. int("abc")
TypeErrorWrong type used in an operation
ZeroDivisionErrorDividing by zero
KeyErrorDictionary key doesn't exist
IndexErrorList index out of range
FileNotFoundErrorFile doesn't exist when opening

Custom Exceptions

class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance!")
    return balance - amount

try:
    withdraw(1000, 5000)
except InsufficientFundsError as e:
    print(e)

Key Takeaways

  • Use try/except to handle errors without crashing your program
  • else runs only if no exception occurred; finally always runs
  • Use raise to trigger your own exceptions, including custom exception classes
  • Catch specific exceptions whenever possible instead of a generic Exception

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →