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!"];
}
Binarian
  • 12,296
  • 8
  • 53
  • 84
Brian Gesiak
  • 6,648
  • 4
  • 35
  • 50
  • this answer may also help: http://stackoverflow.com/a/24010741/1249958 – halilb Jun 03 '14 at 19:21
  • Sorry, should have searched more diligently before submitting a duplicate question! – Brian Gesiak Jun 03 '14 at 19:29
  • 2
    You can add try-catch support for Swift by following the instructions in this article: https://medium.com/@_willfalcon/adding-try-catch-to-swift-71ab27bcb5b8 – William Falcon Oct 13 '14 at 03:50
  • @WilliamFalcon, put it as an answer. Sometimes you have to interact with ObjC library throwing exceptions, your approach seems the only way. – Cfr Feb 10 '15 at 16:58
  • 1
    it is possible in swift 2.0 – Paraneetharan Saravanaperumal Jun 10 '15 at 11:23
  • Fwiw, I bundled @WilliamFalcon's excellent response (as updated for Swift 2 by ravero), into a Carthage lib available at https://github.com/eggheadgames/SwiftTryCatch. Hopefully useful. (Will, happy to contribute back, but I haven't added back CocoaPod support (yet)). – mm2001 Dec 28 '15 at 22:14

2 Answers2

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.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 2
    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. – Brian Gesiak Jun 03 '14 at 19:22
  • 59
    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. – Matt Gallagher Jun 05 '14 at 02:51
  • I submitted a radar: http://openradar.appspot.com/radar?id=5287980646268928 – Brian Gesiak Jun 06 '14 at 02:01
  • 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 said – Mr Bonjour May 07 '15 at 10:18
  • 2
    Swift 2 appears to now have this feature. – Toby Mellor Jun 09 '15 at 16:51
  • @TobyMellor: Citation / sample code (ideally for swift 3, now)? Swift still doesn't seem to let you `try` functions on a FileHandle... – CBHacking Apr 12 '17 at 01:13
0

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

Oscar Swanros
  • 19,767
  • 5
  • 32
  • 48
  • Do you have any data to back up your last sentence, or is it a hunch? – Michael Petrotta Jun 03 '14 at 19:22
  • Basing my answer on the same documentation that manjolds posted on here: http://stackoverflow.com/a/24023248/1011787. `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. – Oscar Swanros Jun 03 '14 at 19:24
  • 2
    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. – holex Jun 12 '14 at 09:16
  • 4
    this is no longer correct, you might want to update your answer to capture possible votes – Dan Beaulieu Dec 27 '15 at 19:02