Exception Handling

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

Python has a number of keywords associated with exception handling:

  • try → block of code to test.
  • except → block of code that runs if an error occurs.
  • else → runs if no exception occurs.
  • finally → always runs (cleanup code, e.g., close file).
  • raise → manually raise an exception.



Catching Exceptions

Catch specific exceptions:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Catch multiple:

try:
    val = int("abc")
except (ValueError, TypeError) as e:
    print("Error:", e)

Catch all (not recommended unless logging/debugging):

try:
    risky_code()
except Exception as e:
    print("Unexpected error:", e)




Raising Exceptions

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return age




Built-in Exceptions

Base Classes:

  • BaseException → root of all exceptions.
  • Exception → base for most user errors.
  • ArithmeticError → base for numeric errors.
  • LookupError → base for indexing/key errors.

Common Everyday Exceptions:

  • Exception → generic base exception.
  • ValueError → invalid value (e.g., int("abc")).
  • TypeError → wrong type (e.g., 3 + "hi").
  • NameError → variable not defined.
  • IndexError → list index out of range.
  • KeyError → dict key not found.
  • ZeroDivisionError → divide by zero.
  • AttributeError → attribute doesn’t exist.
  • FileNotFoundError → missing file.
  • IOError → I/O error (alias of OSError).
  • ImportError → module can’t be imported.
  • ModuleNotFoundError → specific import error.
  • RuntimeError → generic runtime error.
  • StopIteration → end of iterator.
  • AssertionError → failed assert.

Arithmetic Errors:

  • ArithmeticError (base)
    • ZeroDivisionError
    • OverflowError (number too large)
    • FloatingPointError

Lookup Errors:

  • LookupError (base)
    • IndexError
    • KeyError

OS & System Exceptions:

  • OSError → base for system errors
    • FileNotFoundError
    • PermissionError
    • TimeoutError
  • EOFError → end of input reached.
  • KeyboardInterrupt → Ctrl+C pressed.
  • SystemExit → raised by sys.exit().

Other Useful Ones:

  • MemoryError → out of memory.
  • NotImplementedError → abstract method not implemented.
  • IndentationError / TabError → indentation problems.
  • UnicodeError (and subclasses: UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError).




Demonstrate exception handling

def demo_exceptions():
    # Example 1: Simple try/except
    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("Error: division by zero")

    # Example 2: Catch multiple errors
    try:
        num = int("hello") # ValueError
    except (ValueError, TypeError) as e:
        print("Conversion error:", e)

    # Example 3: try/except/else
    try:
        num = int("42")
    except ValueError:
        print("Invalid number")
    else:
        print("Converted successfully:", num)

    # Example 4: try/finally
    try:
        f = open("test.txt", "w")
        f.write("Hello")
    except IOError as e:
        print("File error:", e)
    finally:
        f.close()
        print("File closed safely")

    # Example 5: raise your own exception
    try:
        age = -5
        if age < 0:
            raise ValueError("Age cannot be negative")
    except ValueError as e:
        print("Custom exception caught:", e)

    # Example 6: Generic exception
    try:
        x = unknown_variable
    except Exception as e:
        print("Something went wrong:", e)

demo_exceptions()
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact