1

Swift offers exception-handling capabilities that are useful in situations when errors are out of programmer's control (missing files, dropped connections, et cetera). Although I could use the same mechanism for reporting situations caused by programmer's errors (index out of bounds, range errors, et cetera) I am wondering if that is the intended way of using exceptions.

In Objective-C code a common way to deal with these situations was through asserts. On the other hand, using exceptions was somewhat discouraged in Objective-C, so there may be no one-for-one substitution here.

Similarly, in Java there are checked and unchecked exceptions, with the intention to use unchecked ones for programmer's mistakes.

My understanding is that there is no checked/unchecked distinction among exceptions in Swift. I would like to find out if using exceptions or asserts is the proper way of reporting programmer's mistakes in Swift, or if I should use some other mechanism?

1 Answer 1

1

Despite its similar syntax to Java's exception handling, Swift's do/catch is for handling errors. In other words, Swift does not support exception handling.

See this question for some differences between Java's exception handling and Swift's error handling. An additional item to add to the answer there is that Swift's error handling doesn't provide any stack unwinding.

do/catch is for handling recoverable errors; assert and precondition are for handling unrecoverable programmer errors.

See here for a discussion and a quote from Dave Abrahams on when to use assert vs precondition.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I guess the short answer is "use preconditions".
It depends. If you're trying to identify and remove programmer errors during your building process, then use assert, which will help you to identify when conditions are not met in debug builds. If, for example, you are writing a framework, and you want to guard against unrecoverable violations of some condition in release builds, then use precondition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.