Throwing exceptions quickly
Since we fortunately have exceptions since Swift 2, I wondered if there was a way to throw the thrown exception. Sometimes it just doesn't make sense to surround a statement with a throw-catch clause, because an error only occurs under very specific circumstances. If this is not possible, I would like to know what is a good practice to handle an error that should not be checked every time in Swift? Should I call fatalError
that breaks the program, or should I raise NSException
, which is clearly not the Swifty way, as I can't even catch NSException
in pure Swift I guess.
Thank you for your responses.
If you are writing a function and you want to indicate that something internally went wrong (for example, a condition was not met), fatalError
and preconditionFailure
these are the things that need to be called. Bonus points for guarded use:
guard let myPrecondition = myOptionalPrecondition else { preconditionFailure("Precondition should never be optional here!") }
or
guard somePrecondition else { preconditionFailure() }