Tutorials Logic, IN info@tutorialslogic.com

Python Exception Handling try except finally: Causes and Fixes

Python Exceptions

Error handling lets a program respond to expected problems without crashing in a confusing way.

Use try and except around code that can fail for real-world reasons, such as invalid input, missing files, or network failures.

Do not catch every error blindly. Good error handling fixes expected problems and still lets real bugs become visible.

Errors and Exceptions

Python has two kinds of errors: syntax errors (caught before running) and exceptions (occur at runtime). Exceptions can be caught and handled gracefully using try/except.

Built-in Exceptions

Exception When it occurs
ValueError Wrong value type: int("abc")
TypeError Wrong type: "2" + 2
IndexError List index out of range
KeyError Dict key not found
AttributeError Object has no such attribute
NameError Variable not defined
ZeroDivisionError Division by zero
FileNotFoundError File doesn't exist
ImportError Module not found
StopIteration Iterator exhausted
RuntimeError Generic runtime error
OverflowError Numeric result too large

try except

Catch One Expected Failure

Catch One Expected Failure
# Basic try/except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch multiple exceptions
try:
    value = int(input("Enter a number: "))
    result = 100 / value
    print(f"Result: {result}")
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch multiple in one line
try:
    x = int("abc")
except (ValueError, TypeError) as e:
    print(f"Error: {e}")

# Catch any exception (use sparingly)
try:
    risky_operation()
except Exception as e:
    print(f"Something went wrong: {e}")
    print(f"Error type: {type(e).__name__}")

else and finally

else & finally

else & finally
try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    # Runs only if NO exception occurred
    print(f"File content: {content}")
finally:
    # ALWAYS runs - perfect for cleanup
    print("Done (with or without error)")
    # file.close() would go here

# Real-world pattern: file handling
try:
    with open("data.txt", "r") as f:  # 'with' auto-closes the file
        data = f.read()
except FileNotFoundError as e:
    print(f"Error: {e}")
except PermissionError:
    print("No permission to read this file")
else:
    print(f"Read {len(data)} characters")
finally:
    print("File operation complete")

Raising Exceptions

raise

raise
def set_age(age: int):
    if not isinstance(age, int):
        raise TypeError(f"Age must be an int, got {type(age).__name__}")
    if age < 0 or age > 150:
        raise ValueError(f"Age {age} is out of valid range (0-150)")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(f"ValueError: {e}")

# Re-raise an exception
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Logging the error...")
    raise   # re-raises the same exception

# Raise from another exception (exception chaining)
try:
    data = int("abc")
except ValueError as e:
    raise RuntimeError("Failed to process data") from e

Custom Exceptions

Custom Exception Classes

Custom Exception Classes
# Custom exceptions inherit from Exception
class InsufficientFundsError(Exception):
    def __init__(self, amount: float, balance: float):
        self.amount = amount
        self.balance = balance
        super().__init__(
            f"Cannot withdraw ${amount:.2f}. Balance: ${balance:.2f}"
        )

class BankAccount:
    def __init__(self, balance: float = 0):
        self.balance = balance

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

account = BankAccount(100)

try:
    account.withdraw(150)
except InsufficientFundsError as e:
    print(f"Error: {e}")
    print(f"Tried to withdraw: ${e.amount}")
    print(f"Available: ${e.balance}")
Exception handling check

Can You Handle Failures Clearly?

5 checks
  • Catch the specific exception you know how to handle.
  • Keep try blocks small so the failing operation is obvious.
  • Use else for code that should run only when no exception occurred.
  • Use finally for cleanup that must always run.
  • Avoid hiding real bugs with broad empty except blocks.

Exception Decisions

0 of 2 checked

Q1. Why should a try block usually stay small?

Q2. Which exception is a natural fit for invalid numeric input?

Exception Handling Traps

  • Catching everything

    Catch specific expected exceptions such as ValueError or FileNotFoundError.
  • Hiding the error message

    Show or log enough detail to understand what failed.
  • Putting too much code inside try

    Wrap only the statement that can fail so the cause stays clear.

Try this next

Catch a Failure Clearly

0 of 3 completed

  1. Convert text to int and catch ValueError with a helpful message.
  2. Read a path and catch FileNotFoundError without hiding other bugs.
  3. Raise ValueError when a function receives a negative quantity.

Questions About Error Handling

Avoid broad catches unless you log or re-raise carefully. Catch the specific error you know how to handle.

finally runs whether an error happened or not. Use it for cleanup that must always happen.

Raise an error when a function receives invalid data or reaches a state it cannot safely handle.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.