PyObjC Framework: ExceptionHandling

12.1 · active · verified Tue Apr 14

This library provides Python wrappers for the macOS `ExceptionHandling` framework, enabling Python applications to interact with Objective-C's exception mechanisms. It's part of the larger PyObjC bridge, which allows full-featured Cocoa applications to be written in pure Python. PyObjC is actively maintained, with new versions typically released to align with macOS SDK updates and Python version support. The current version is 12.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how PyObjC bridges Python exceptions when Objective-C code calls into Python. By setting `objc.setVerbose(True)`, you can observe more detailed Python stack traces in the console when exceptions cross the language boundary. The `ExceptionHandling` framework itself is low-level, so this example focuses on PyObjC's general exception bridging behavior, which is the primary user-facing aspect of exception interaction.

import objc
from Foundation import NSObject, NSLog

# Enable verbose logging for PyObjC to see detailed stack traces
# when exceptions cross the Python/Objective-C boundary.
# This is key for understanding issues related to ExceptionHandling.
objc.setVerbose(True)

class MyPythonException(Exception):
    """A custom Python exception to demonstrate bridging."""
    pass

# Define an Objective-C class (via Python subclassing NSObject)
class MyObjCClass(NSObject):
    def init(self):
        self = super().init()
        if self:
            NSLog("MyObjCClass initialized in Python")
        return self

    def triggerPythonException_(self, arg):
        """An Objective-C callable method that might raise a Python exception."""
        NSLog("Objective-C calling Python method to trigger exception with arg: %@", arg)
        if arg == "error":
            raise MyPythonException("An error occurred in Python!")
        return "Python successfully processed: " + arg

if __name__ == "__main__":
    obj = MyObjCClass.alloc().init()

    # Example 1: Call method that triggers a Python exception
    print("\n--- Attempting to trigger an exception ---")
    try:
        # When Python raises an exception, PyObjC translates it into an
        # Objective-C exception. If caught back in Python, it manifests as objc.error.
        result = obj.triggerPythonException_("error")
        print(f"Result (should not be reached): {result}")
    except objc.error as e:
        print(f"Caught Objective-C error (originally Python exception): {e}")
    except MyPythonException as e: # This would not be caught directly here
        print(f"Caught Python exception directly: {e}")

    # Example 2: Call method that succeeds
    print("\n--- Attempting a successful call ---")
    result = obj.triggerPythonException_("success")
    print(f"Successful call result: {result}")

view raw JSON →