Exceptions: A metaphor

Concept of Raising Exceptions and Handling Exceptions

  • Metaphor: Welder and Welding Pipes

    • Task of the Welder: Welding pipes is the primary responsibility of the welder.

    • Normal Operation:

      • The welder continues to work until an issue arises.

      • They are actively trying to weld the pipes.

Handling Issues During Welding

  • Issues May Arise: When problems occur, the welder must stop to handle them.

    • Planned Issues:

      • The welder identifies known problems and has specific plans to address them.

      • Examples of Planned Issues:

        • Melted metal is dripping: The welder stops to wipe it off.

        • Broken electrode: The welder replaces it immediately.

  • Unplanned Issues:

    • New problems not anticipated must be dealt with differently.

      • Example of an Unplanned Issue:

        • Welding too hard may result in a hole in the pipe.

        • This issue was not planned for, leaving the welder unsure of how to proceed.

        • The welder calls the supervisor for assistance with this unplanned issue.

Relation to Python Exception Handling

  • Executing a Method: When a method is running in Python, it can encounter exceptions.

  • Execution Stops:

    • Similar to the welder stopping work, code execution halts when an exception occurs.

    • The exception must be handled to continue execution.

  • Handling Exceptions:

    • If the method can handle the exception on the spot, normal execution resumes.

    • If the method does not handle it, the exception is passed to the method that invoked it (the calling method).

  • Calling Stack:

    • Each method is part of a calling stack.

    • When an exception occurs, it bubbles up from the current method to its caller until it is handled or the program crashes.

      • If a caller can handle the exception, it takes care of it.

      • If no method can handle it, the program terminates.