Book a call
Menu

Swift Cannot Catch an NSException: The Twenty-Line Objective-C Shim Behind Our Audio Engine

Happy Coders team26 Nov 202613 min read
Swift Cannot Catch an NSException: The Twenty-Line Objective-C Shim Behind Our Audio Engine

Swift error handling looks complete. You mark a function throws, you wrap the call in do / catch, and every failure arrives as a value you can inspect. Then you call into AVFoundation, the framework raises an Objective-C exception instead, and the process terminates with your catch block sitting there unused. No error, no log line from your code, just a crash report that ends in objc_exception_throw.

We hit this in HappyRec, our screen recorder for Mac, in the part that runs the microphone through a live effects chain for the voice changer. On some machines, with some combinations of input device, sample rate and voice processing, AVAudioEngine refuses a connection or refuses to start, and it says so by raising an NSException. This post is about the small Objective-C target that makes those exceptions survivable: what is in it, how a Swift package wires it in, exactly where HappyRec calls it, and, just as important, what the app does after an exception has been caught. We have written before about the fallback ladder that the voice changer climbs down when an audio graph fails. This is the piece underneath it, in detail.

Why Swift cannot catch it

Swift errors and Objective-C exceptions share a word and nothing else. A Swift throw is an ordinary return path: the function hands back an error value, the caller checks it, and the compiler makes you deal with it. Nothing is unwound behind your back.

An Objective-C exception is a real stack unwind, the same machinery C++ uses. objc_exception_throw walks up the stack looking for an @catch handler. Swift code has no @catch, and Swift’s catch is not one. If no Objective-C handler is found, the runtime calls the uncaught exception handler and the process aborts.

// This compiles, and it does not do what it looks like.
do {
    try engine.start()
    engine.connect(input, to: preMixer, format: hwFormat)   // raises NSException
} catch {
    print("never reached for an NSException")             // process is already gone
}

On Apple’s platforms, exceptions are reserved for programmer errors: things like an out-of-range index, or in our case an audio graph operation that violates one of the engine’s internal conditions. The convention is that you fix the code rather than handle the exception. That is a reasonable rule for an array index. It is not reasonable for an audio engine whose behaviour depends on hardware we do not control. The same code that works on one Mac can raise on another, for example because a microphone reports a format the engine will not accept at that point in the graph, or because switching on voice processing changes the input node’s format. We cannot fix the user’s microphone. We can stop it from crashing the app.

Swift errors compared with Objective-C exceptions
Same word, different machinery. Swift's catch only sees the left side.

The shim: one function, one file

The only way to catch an Objective-C exception is in Objective-C. So the app has a target that exists solely for that. Its public header declares one function:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/// Runs the block and returns nil on success, or an NSError describing any
/// NSException it raised. Swift cannot catch Objective-C exceptions (AVFoundation
/// throws them for invalid audio-graph operations), so this shim converts them.
FOUNDATION_EXPORT NSError * _Nullable HRCatchException(void (NS_NOESCAPE ^block)(void));

NS_ASSUME_NONNULL_END

And the implementation is the whole target:

#import "ObjCExceptionCatcher.h"

NSError *HRCatchException(void (NS_NOESCAPE ^block)(void)) {
    @try {
        block();
        return nil;
    } @catch (NSException *exception) {
        // exception.reason carries the useful text ("required condition is
        // false: isInputConnToConverter" and friends); name is the fallback.
        NSString *description = exception.reason.length > 0 ? exception.reason : exception.name;
        NSMutableDictionary *info = [NSMutableDictionary dictionary];
        if (description) { info[NSLocalizedDescriptionKey] = description; }
        if (exception.name) { info[@"HRExceptionName"] = exception.name; }
        if (exception.userInfo) { info[@"HRExceptionUserInfo"] = exception.userInfo; }
        return [NSError errorWithDomain:@"HRObjCException" code:1 userInfo:info];
    }
}

A few choices in those twenty lines are deliberate.

It returns an NSError, not a Boolean. Imported into Swift, the function becomes HRCatchException(_ block: () -> Void) -> Error?. nil means the block ran to completion. Anything else is a normal Swift Error that can be thrown, logged and shown in the interface, so the rest of the app never needs to know that an Objective-C exception was involved.

The message comes from reason, with name as a fallback. AVFoundation’s exceptions mostly have the generic name com.apple.coreaudio.avfaudio. The useful part is the reason, text such as required condition is false: isInputConnToConverter, which tells you which internal check failed. That string becomes the error’s localizedDescription, and it is what ends up in our diagnostic log.

Nothing is thrown away. The exception’s name and its userInfo dictionary are kept under their own keys, in an error domain of their own, HRObjCException. When a crash report or a support log comes in, we can tell an exception that was caught and converted from an error the app created itself.

The block is NS_NOESCAPE. The block runs synchronously and is never stored, and saying so lets Swift pass a non-escaping closure. In practice that means call sites can use [self] and touch the object’s properties directly, without the noise of an escaping closure.

Wiring it into a Swift package

HappyRec is built with Swift Package Manager, which handles mixed-language projects cleanly as long as each language sits in its own target. A target with a .m file and an include/ folder is compiled as C-family code, and the headers in include/ become a module that Swift can import:

Sources/
  ObjCExceptionCatcher/
    ObjCExceptionCatcher.m
    include/
      ObjCExceptionCatcher.h      <- public header, becomes the Swift module
  VoiceDSP/ ...
  HappyRec/ ...                   <- the app, written in Swift

The package manifest then names it as an ordinary dependency of the app:

// swift-tools-version:5.9
let package = Package(
    name: "HappyRec",
    platforms: [.macOS(.v13)],
    targets: [
        // Traps Objective-C exceptions (AVFoundation raises them for invalid
        // audio-graph operations) so Swift can handle them instead of crashing.
        .target(name: "ObjCExceptionCatcher"),
        .target(name: "VoiceDSP", cxxSettings: [.headerSearchPath("../../Vendor")]),
        .executableTarget(
            name: "HappyRec",
            dependencies: ["VoiceDSP", "ObjCExceptionCatcher"]
        ),
    ],
    cxxLanguageStandard: .cxx17
)

There is no bridging header and no Xcode project setting to keep in sync. A Swift file that needs the function writes import ObjCExceptionCatcher, and the compiler takes care of the rest. In HappyRec exactly one file does: the voice changer’s audio engine. Keeping the import in one place is a quiet guard against the shim spreading into code that has no business catching exceptions.

Where HappyRec calls it

Every call that can raise during graph set-up runs inside the shim. There are three places, and they nest.

The connections. The voice changer’s effects chain runs the microphone through a mixer, an EQ, a pitch shifter, distortion and, in the full version, reverb. Each engine.connect can raise if the formats on either side are not acceptable, so all of them run in one trapped block:

if let error = HRCatchException({ [self] in
    engine.connect(input, to: preMixer, format: hwFormat)
    engine.connect(preMixer, to: eq, format: stereo)
    engine.connect(eq, to: timePitch, format: stereo)
    engine.connect(timePitch, to: distortion, format: stereo)
    if attempt == .fullChain {
        engine.connect(distortion, to: reverb, format: stereo)
    }
    engine.connect(lastNode, to: engine.mainMixerNode, format: stereo)
}) {
    throw HappyRecError("Audio setup failed — \(error.localizedDescription)")
}

Notice that the first connection uses the hardware format and the rest use a stereo processing format. The engine will not place a converter directly after the input node, so the connection out of it must match whatever the device reports. That is one of the conditions that, when broken, arrives as an exception rather than an error.

Prepare and start. engine.start() is a Swift throws function, and it can also raise an Objective-C exception. So it is wrapped twice: try? for the Swift error, the shim for the exception. Then the code checks the only thing that actually matters, whether the engine is running:

if let error = HRCatchException({ [self] in
    engine.prepare()
    try? engine.start()
}) {
    throw HappyRecError("Could not start the microphone engine — \(error.localizedDescription)")
}
guard engine.isRunning else {
    throw HappyRecError("The microphone engine did not start.")
}

The isRunning check is not redundant. Between a swallowed Swift error and a trapped exception, it is the one signal that covers every way of failing.

The whole attempt. Around both of those, the entire build of one graph variant runs inside a third trap:

var swiftError: Error?
if let objcError = HRCatchException({ [self] in
    do { try build(attempt) } catch { swiftError = error }
}) {
    throw HappyRecError("Audio graph failed — \(objcError.localizedDescription)")
}
if let swiftError { throw swiftError }

The comment in the source explains why: the trap must cover the whole attempt, including teardown, because a failed engine can also raise from stop() or while being replaced. The inner traps give precise messages (“Audio setup failed”, “Could not start the microphone engine”). The outer one is the safety net for anything else in the attempt, such as creating a fresh engine or reading the input node’s format. Swift errors thrown inside the block are carried out through a captured variable, because the block itself cannot throw: its signature is void (^)(void).

The three places HappyRec traps exceptions
Precise messages inside, a safety net outside.

After the catch: assume the engine is ruined

Catching the exception is half the job. The other half is deciding what state the program is in afterwards, and the honest answer is: not a state you can trust.

When an exception unwinds out of AVFoundation, the engine’s internal graph may be half-built. Some nodes are connected and some are not; the engine believes conditions hold that do not. And the unwind passes through the Swift closure on its way to the @catch. Swift does not run cleanup code for frames that an Objective-C exception passes through, so any reference counting or defer blocks in those frames are simply skipped. The process survives, but some memory may leak, and the objects involved should be treated as damaged.

HappyRec takes that seriously in three ways.

It never reuses a failed engine. Every attempt starts by building a completely new AVAudioEngine and a new set of effect nodes. Trying to disconnect and reconnect the old graph is exactly the kind of operation that raised in the first place.

It never releases a failed engine either. This was the surprise. Deallocating an engine whose graph configuration had failed crashed with a segmentation fault inside -[AVAudioEngine dealloc], while it disconnected the corrupted graph. That is a hard crash, not an exception, and no shim can catch it. So failed engines are kept alive on purpose, for the rest of the process’s life:

/// Engines whose graph configuration failed. Deallocating one crashes
/// with SIGSEGV inside -[AVAudioEngine dealloc] (AUGraph disconnection
/// on a corrupted graph), so they are intentionally kept alive for the
/// process lifetime instead. Healthy engines are released normally.
private var quarantinedEngines: [AVAudioEngine] = []
private var lastEngineCorrupted = false

private func freshEngine() {
    tappedNode = nil
    renderer = nil
    if lastEngineCorrupted {
        quarantinedEngines.append(engine)
        lastEngineCorrupted = false
    }
    engine = AVAudioEngine()
    // ... new mixer, EQ, pitch, distortion and reverb nodes, all attached
}

A deliberate, bounded leak is a much better outcome than a crash. Each failed attempt costs one engine’s worth of memory, and there are at most three attempts.

It remembers what worked. Because each failure leaks an engine, the app stores the name of the graph variant that last started successfully, and tries that one first next time. A machine that can only run the plain microphone tap does not pay for two failed attempts every time recording starts.

What happens after an exception is caught
The catch is the easy part. The recovery decides whether it works.

If every variant fails, the error from the last attempt is thrown to the caller, with the exception’s reason in its message, and it ends up in the interface and the diagnostic log. If the simplest variant works, recording carries on with a plain tap on the microphone, and effects are applied through a separate offline renderer instead of the live chain.

What the shim does not do

It is worth being precise about the limits, because a catch-all wrapper invites over-use.

  • It does not catch crashes. A segmentation fault, a failed precondition in Swift, or an abort inside a framework is not an exception. The dealloc crash above is the proof: no wrapper helps there.
  • It catches NSException, not C++ exceptions. The handler is @catch (NSException *exception). A C++ exception that escapes a framework would not match it. That has not been a problem for AVFoundation’s graph errors, which are all NSExceptions, but it is a reason not to treat the shim as universal.
  • It does not make the code after it safe. It only converts a crash into an error. Everything the block touched has to be considered broken, which is why the recovery strategy matters more than the wrapper.
  • It is not for your own code. If Swift code you wrote can fail, make it throw. The shim is for crossing into a framework that uses exceptions for conditions you cannot prevent.

Testing a shim like this

The behaviour that matters is easy to check without any audio hardware. Call the function with a block that raises on purpose, for example an Objective-C helper that calls [NSException raise:format:], or an out-of-range objectAtIndex: on an NSArray, and assert three things: the function returns an error rather than crashing the test runner, the error’s description is the exception’s reason, and the name survives under its own key. Then call it with a block that does nothing and assert it returns nil.

The audio side is harder to test, because the failures depend on hardware. What can be tested is the decision logic around it: given that attempt one fails, does the code build a fresh engine, mark the old one for quarantine, and move to the next variant? Keeping the engine calls behind a small number of functions makes that logic readable, even when it is not convenient to unit test.

Making the failures visible

A caught exception is only useful if someone can read it later. Two small habits in the voice engine make that possible.

The first is logging the input before building anything. For every attempt, the engine logs which graph variant it is trying and the hardware sample rate and channel count the microphone reported. Format mismatches are the most common reason a connection is refused, so that one line usually explains the failure on its own.

The second is the shim itself. Once exceptions become errors, they also become log lines carrying the engine’s own reason text, and each failed variant is logged with that message before the next one is tried. A crash only tells you where you were. A caught exception tells you why, and with the hardware format logged beside it, which machine condition caused it.

Checklist for using AVFoundation, or any exception-raising framework, from Swift

  • Know which calls can raise. For AVAudioEngine: connect, prepare, start, installTap, and teardown on a failed engine.
  • Put a small Objective-C target in the package with one function that runs a block in @try / @catch and returns an NSError.
  • Keep reason, name and userInfo in the error. You will want them in a support log.
  • Import the shim in as few files as possible, and trap whole operations, not single lines, so teardown is covered.
  • After a catch, throw the object away and build a new one. Do not reuse it, and check whether releasing it is safe at all.
  • Have a less ambitious fallback, and remember which one worked on this machine.

Questions we were asked

Is catching exceptions on Apple platforms not considered bad practice?

For your own logic, yes: use Swift errors. But when a framework raises for conditions that depend on the user’s hardware, the alternative is a crash on someone else’s machine that you cannot reproduce. Catching it, discarding the damaged object and falling back is the safer engineering choice.

Could the same thing be written in Swift with a library?

Any solution ends up as Objective-C at the bottom, because only Objective-C can contain an @catch. A library just hides the same file. Ours is twenty lines and has no dependencies, so we keep it.

Does the leak from quarantined engines grow over time?

It is bounded. An engine is kept only when an attempt fails, and the app starts with the variant that worked last time, so on a given machine the failures happen once rather than at every recording.

HappyRec is our free screen recorder for Mac, Windows, Chrome and Edge, built and maintained by our team in India. We build native Mac and desktop apps for clients worldwide too. See HappyRec.

Keep reading

Related articles