Crashlytics reports that the following line is sometimes throwing a NSInternalInconsistencyException
:
let attrStr = try NSMutableAttributedString(
data: modifiedFont.data(using: String.Encoding.unicode,
allowLossyConversion: true)!,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
Here I'm not as interested in why this happens (there's a 3 year old question about it) as I am in catching/handling this exception. I've tried to do it like this:
do {
let attrStr = try NSMutableAttributedString(
data: modifiedFont.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
} catch {
self.attributedText = nil
self.text = text.stripHTML()
}
... but this is not working for some reason - the exception is still being reported.
Am I trying to catch it in the right way? Can it be caught at all? If not, what are my options?
Swift converts Objective-C methods with nullable returns and trailing NSError**
parameters to methods that throw in Swift. But, in Objective-C, you can also throw exceptions. These are distinct from NSError
s and Swift does not catch them. In fact there is no way to catch them in Swift. You would have to write an Objective-C wrapper that catches the exception and passes it back in some way Swift can handle.
You can find this in the Apple document Handling Cocoa Errors in Swift in the Handle Exceptions in Objective-C Only section.
So it turns out that you can catch it, but it is worthwhile considering whether you should (see comments from @Sulthan below). To the best of my knowledge most Apple frameworks are not exception-safe (see: Exceptions and the Cocoa Frameworks) so you can't just catch an exception and continue on as if nothing happened. Your best bet is save what you can and exit as soon as possible. Another issue to consider is that unless you rethrow the exception, frameworks such as Crashlytics won't report it back to you. So, if you did decide to catch it you should log it and/or rethrow it so that you know that it is happening.