#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
•Question 12 of 41easy

Exception Handling in Python

Handling errors with try-except.

What You'll Learn

  • How exception handling works in Python
  • try, except, else, finally blocks
  • Catching specific vs general exceptions
  • Raising and creating custom exceptions
  • Best practices for error handling

Understanding Exceptions

Exceptions are errors that occur during program execution. Instead of crashing, Python allows you to catch and handle these errors gracefully using try-except blocks.

Common exceptions:

  • ValueError - Wrong value type
  • TypeError - Wrong operation for type
  • KeyError - Dict key not found
  • IndexError - List index out of range
  • FileNotFoundError - File doesn't exist
  • ZeroDivisionError - Division by zero

Basic Try-Except

code.pyPython
# Without handling - program crashes
# result = 10 / 0  # ZeroDivisionError!

# With handling - graceful error recovery
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
    result = 0

print(f"Result: {result}")  # Program continues

Catching Multiple Exceptions

code.pyPython
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch multiple in one except
try:
    # some code
    pass
except (ValueError, TypeError) as e:
    print(f"Value or Type error: {e}")

# Catch all exceptions (use sparingly)
try:
    risky_operation()
except Exception as e:
    print(f"An error occurred: {e}")

The Full Try Block

code.pyPython
try:
    file = open("data.txt", "r")
    data = file.read()
    number = int(data)
except FileNotFoundError:
    print("File not found!")
    number = 0
except ValueError:
    print("File doesn't contain a valid number!")
    number = 0
else:
    # Runs ONLY if no exception occurred
    print("File read successfully!")
finally:
    # ALWAYS runs, even if exception occurred
    print("Cleanup: closing file if open")
    try:
        file.close()
    except:
        pass

When Each Block Runs

BlockWhen it runs
tryAlways (main code)
exceptOnly when matching exception occurs
elseOnly when NO exception in try
finallyALWAYS (cleanup code)

Raising Exceptions

code.pyPython
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")
    return age

# Catching raised exceptions
try:
    age = validate_age(-5)
except ValueError as e:
    print(f"Invalid age: {e}")

# Re-raising exceptions
try:
    validate_age(-5)
except ValueError:
    print("Logging error...")
    raise  # Re-raise the same exception

Custom Exceptions

code.pyPython
# Define custom exception
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        message = f"Cannot withdraw {amount}. Balance: {balance}"
        super().__init__(message)

# Use custom exception
class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount
        return amount

# Handle custom exception
account = BankAccount(100)
try:
    account.withdraw(150)
except InsufficientFundsError as e:
    print(f"Error: {e}")
    print(f"Available: {e.balance}")

Best Practices

code.pyPython
# BAD: Catching all exceptions silently
try:
    risky_code()
except:
    pass  # Hides all errors!

# GOOD: Catch specific exceptions
try:
    risky_code()
except SpecificError as e:
    logger.error(f"Expected error: {e}")
    handle_error()

# GOOD: Use context managers instead of try-finally
# Instead of:
try:
    f = open("file.txt")
    data = f.read()
finally:
    f.close()

# Use:
with open("file.txt") as f:
    data = f.read()

# GOOD: Check before acting (when possible)
# Instead of:
try:
    value = my_dict[key]
except KeyError:
    value = default

# Use:
value = my_dict.get(key, default)

Interview Tip

When asked about Python exception handling:

  1. try-except catches errors, prevents crashes
  2. finally always runs (cleanup code)
  3. else runs only if no exception occurred
  4. Catch specific exceptions, not bare except:
  5. raise to throw exceptions, create custom ones
  6. Use context managers (with) when possible