Skip to content

    Exceptions & File Handling

    Python · Beginner

    Definition

    Exceptions signal errors at runtime and are handled with try/except; files are read and written with open().

    Robust programs handle errors gracefully and work with data files.

    Diagram

    try→ except→ else→ finally

    Flowchart

    try risky codeexcept specific errorelse when no errorfinally always runs

    Example: Safe division

    try:
        print(10 / 0)
    except ZeroDivisionError:
        print('Cannot divide by zero')

    Output: Cannot divide by zero

    Key points

    • Use 'with open()' to auto-close files
    • Catch specific exceptions
    • raise creates your own errors

    Interview questions

    Why use 'with'?

    It closes the file even if an error occurs.

    More Python topics