print(NSError.init()) -> crash

I’m surprised that NSError does not override init() with at least a deprecation warning, or with a fatalError with a good error message ”Use init:domain:code:userInfo instead”. Because the current situation is not so good DX, we get runtime crash with unclear EXC_BREAKPOINT.

Could we not do:

@available(*, unavailable)
public override init() { … }

?

(And yea trivially avoided by not using this init, or by using our own error type. But this is a trap which at least should have a clear error message, but best be made impossible altogether. I got this with Macbook Pro M2 Max, Tahoe, Xcode 26.1.1)

1 Like

On macOS, NSError actually does log the following when you call NSError():

-[NSError init] called; this results in an invalid NSError instance. It will raise an exception in a future release. Please call errorWithDomain:code:userInfo: or initWithDomain:code:userInfo:. This message shown only once.

It's likely that the environment in which you were running your code is not displaying the output logging. The error message does indicate that it may become an exception (which would trigger a crash) in a future release. Changing it to unavailable or adding the exception is likely possible but may result in breaking apps that are creating an NSError like this but not using it in practice.

Since this behavior exists in the Apple OS versions of Foundation but not in the open source swift-corelibs-foundation for non-Apple platforms, I recommend filing a feedback via Feedback Assistant about this (and if you do please share the number here)

1 Like

I wonder the same... Any good thing I could do with NSError() otherwise why do we even have it?

NSError inherits from NSObject, and NSObject has init(), so even if it had an unavailable annotation, you could still call NSError.init() indirectly:

(NSError.self as NSObject.Type).init()

(But yes, it should still have an unavailable annotation to prevent the straightforward unintentional NSError())

4 Likes

You are right.

Interestingly calling NSError() gives me this promise in the console: "It will raise an exception in a future release".

Filed, under FB22588287

3 Likes