try-catch exceptions in Swift [duplicate]
Asked Answered
R

2

29

Is it possible to catch exceptions in Swift? Given the following code:

NSException.raise(NSRangeException,
    format: "Now you've gone too far!",
    arguments: CVaListPointer(fromUnsafePointer: UnsafePointer()))

Is it possible to prevent the exception from crashing the entire program? That is, what is the Swift equivalent of the following in Objective-C:

@try {
    [NSException raise:NSRangeException format:@"Now you've gone too far!"];
}
Roadability answered 3/6, 2014 at 19:12 Comment(6)
this answer may also help: https://mcmap.net/q/128083/-error-handling-in-swift-languageTeferi
Sorry, should have searched more diligently before submitting a duplicate question!Roadability
You can add try-catch support for Swift by following the instructions in this article: medium.com/@_willfalcon/adding-try-catch-to-swift-71ab27bcb5b8Caecilian
@WilliamFalcon, put it as an answer. Sometimes you have to interact with ObjC library throwing exceptions, your approach seems the only way.Alber
it is possible in swift 2.0Knighthead
Fwiw, I bundled @WilliamFalcon's excellent response (as updated for Swift 2 by ravero), into a Carthage lib available at github.com/eggheadgames/SwiftTryCatch. Hopefully useful. (Will, happy to contribute back, but I haven't added back CocoaPod support (yet)).Maggiemaggio
A
12

It doesn't have exception handling, and this discussion in the developer forum discusses why it may be so:

but keep in mind that Cocoa and Cocoa Touch traditionally don't intend for you to catch exceptions; they intend for you to not cause them to be thrown in the first place. Ordinary errors should be handled with optional types and inout NSError parameters; you should address any situation that causes an assertion to fail (which seems to be the only exception-throwing mechanism in Swift) by writing better code.

Atone answered 3/6, 2014 at 19:19 Comment(6)
That's very unfortunate. I'm aware that try-catch was never really encouraged in Objective-C, but currently there's no way to unit test whether Swift code throws an exception. XCTAssertThrows is not available in .swift tests, and without try-catch, there's no way to write a passing test that involves exceptions.Roadability
That comment from the forums is wrong. Foundation throws exceptions in a number of places that need to be caught for the program to function normally. The best example is writing to an NSFileHandle when the NSFileHandle experiences a broken pipe (e.g. a server writing to a connection after the client has closed the connection). There is no other way to detect this condition other than writing to the connection and it is a valid, non-fatal scenario. Without exception handling, Swift programs cannot implement server-like functionality using the Cocoa APIs.Larine
I submitted a radar: openradar.appspot.com/radar?id=5287980646268928Roadability
I find it quite disturbing to throw error from the API, and don't let the swift language handle them. I just experienced the situation and really don't appreciate it. Sorry to be non-constructive, but some things need to be saidHydrate
Swift 2 appears to now have this feature.Bascomb
@TobyMellor: Citation / sample code (ideally for swift 3, now)? Swift still doesn't seem to let you try functions on a FileHandle...Cissie
T
0

I believe that, as of today, Swift does not support this. It will most likely be added on future betas.

Transsonic answered 3/6, 2014 at 19:17 Comment(4)
Do you have any data to back up your last sentence, or is it a hunch?Senior
Basing my answer on the same documentation that manjolds posted on here: https://mcmap.net/q/245822/-try-catch-exceptions-in-swift-duplicate. Cocoa and CocoaTouch traditionally don't intend for you to catch exceptions, however they're still supported. That's why I said "most likely" — even though they don't encourage their use, they still provide that option.Transsonic
probably, you assumption about "It will most likely be added on future betas." is not correct according to the official docs, because they clearly indicate that it won't happen in the future either. you can throw exception in Swift, but it cannot be caught in runtime therefore those are always critical exceptions.Fylfot
this is no longer correct, you might want to update your answer to capture possible votesCompression

© 2022 - 2024 — McMap. All rights reserved.