Swift - How to Deal with Uncaught Exception

Uncaught Error/Exception Handling in Swift

Swift has no mechanism to catch all arbitrary runtime exceptions.
The reasons are explained in

  • [swift-users] "business applications market" flame

in the swift-users forum. Extract:

Swift made a conscious choice not to include exceptions thrown through
arbitrary stack frames not because it was technically impossible, but
because its designers judged the costs to be too high.

The problem is this: if a piece of code is going to exit early because
of an error, it has to be written to handle that early exit. Otherwise
it will misbehave—fail to deallocate memory, fail to close file
handles/sockets/database connections/whatever, fail to release locks,
etc. In a language like Java, writing truly exception-safe code
requires a ridiculous quantity of try/finally blocks. That's why
nobody does it. They make judgements about which exceptions they're
likely to see and which resources are dangerous to leak, and only
protect their code against those specific anticipated conditions. Then
something unforeseen happens and their program breaks.

This is even worse in a reference-counted language like Swift because
correctly balancing the reference counts in the presence of exceptions
basically requires every function to include an implicit finally block
to balance all the retain counts. This means the compiler has to
generate lots of extra code on the off chance that some call or
another throws an exception. The vast majority of this code is never,
ever used, but it has to be there, bloating the process.

Because of these problems, Swift chose not to support traditional
exceptions; instead, it only allows you to throw errors in
specially-marked regions of code. But as a corollary, that means that,
if something goes really wrong in code that can't throw, all it can
really do to prevent a disaster is crash. And currently, the only
thing you can crash is the entire process.

For more information, see

  • Error Handling Rationale and Proposal

Handle all unhandled exceptions swift

You can set NSSetUncaughtExceptionHandler in your AppDelegate, refer to this post

But Swift does not fully support it, as explain in this post, you need to do it in Objective-C

EDIT

Thanks for Martin R's comment, Swift now supports it.

Exception is not being caught

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 NSErrors 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.

Terminating With Uncaught Exception Of Type NSException Timer Swift Crash

You are passing the wrong target to the timer. You want to pass clickClass, not self. And the selector should not reference the variable, it should reference the class.

timer = Timer.scheduledTimer(timeInterval: 1, target: clickClass, selector: #selector(playSound.repeatSound), userInfo: nil, repeats: true)

You should also take care to name things properly. Class, struct, and enum names should start with uppercase letters. Variable, function, and case names should start with lowercase letters.

terminating with uncaught exception of type NSException in Swift 5

Maybe something like this

var islem: String = screenTextfield.text!

if let number = Int(String(islem.last!)) {
print(number)
}
else {
islem.removeLast()
}

let exp = NSExpression(format: islem)
if let result = exp.expressionValue(with: nil, context: nil) as? NSNumber {
islemLabel.text = String(result.doubleValue)
}
else {
makeAlert(title: "Error", message: "Wrong math type")
}

Terminating app due to uncaught exception Swift

Fixed. I Removed the let loginController = LoginViewController(),
I created a new segue and now do self.performSegue(withIdentifier: "logOut", sender: self), works perfectly

Handle uncaught exception valueForUndefinedKey in Swift

You must find a better solution by talking to lib dev

You can use Mirror reflection and check its objects label

let myClass = Mirror(reflecting: MyClass())
for (_, attr) in myClass.children.enumerated() {
if let propertyName = attr.label, propertyName == "myProperty"{
print(propertyName, attr.value)
}
}


Related Topics



Leave a reply



Submit