61

The biggest misunderstanding for me in Swift is the throws keyword. Consider the following piece of code:

func myUsefulFunction() throws

We cannot really understand what kind of error it will throw. The only thing we know is that it might throw some error. The only way to understand what the error might be is by looking at the documentation or checking the error at runtime.

But isn't this against Swift's nature? Swift has powerful generics and a type system to make the code expressive, yet it feels as if throws is exactly opposite because you cannot get anything about the error from looking at the function signature.

Why is that so? Or have I missed something important and mistook the concept?

6
  • Somewhat related: Can I restrict the type that a function throws in Swift?
    – Hamish
    Commented Nov 21, 2016 at 11:04
  • There also was a discussion on the Swift Evolution mailing list about this.
    – Hamish
    Commented Nov 21, 2016 at 11:14
  • @Hamish I realize I was bit too brief in my thoughts above: I tried to first cover the simplified scenario where we only have functions that throws: in this case, we can naturally annotate the error type. What I stated in the following clause in my comment was based on the misconception that rethrows mustn't necessarily be thrown by arguments to the rethrowing functions, but from any throwing function used in its body (which, in itself, may just be re-throwing its propagated error). In case of the latter, I believe we'd need to investigate the call stack to see where the initial ...
    – dfrib
    Commented Nov 21, 2016 at 12:31
  • ... error propagated from, as we do not know from the function signature of such a rethrowing function which types it may rethrow (alternative, we would be very limited in how to use throwing functions in the body of a rethrows function). But again, this was all based on the misconception that error thrown from rethrows functions aren't necessarily thrown from its arguments.
    – dfrib
    Commented Nov 21, 2016 at 12:32
  • @dfri I guess with rethrows - either your higher level function should throw the same error or should map to another kind of error
    – Noobass
    Commented Nov 21, 2016 at 12:33

3 Answers 3

41

I was an early proponent of typed errors in Swift. This is how the Swift team convinced me I was wrong.

Strongly typed errors are fragile in ways that can lead to poor API evolution. If the API promises to throw only one of precisely 3 errors, then when a fourth error condition arises in a later release, I have a choice: I bury it somehow in the existing 3, or I force every caller to rewrite their error handling code to deal with it. Since it wasn't in the original 3, it probably isn't a very common condition, and this puts strong pressure on APIs not to expand their list of errors, particularly once a framework has extensive use over a long time (think: Foundation).

Of course with open enums, we can avoid that, but an open enum achieves none of the goals of a strongly typed error. It is basically an untyped error again because you still need a "default."

You might still say "at least I know where the error comes from with an open enum," but this tends to make things worse. Say I have a logging system and it tries to write and gets an IO error. What should it return? Swift doesn't have algebraic data types (I can't say () -> IOError | LoggingError), so I'd probably have to wrap IOError into LoggingError.IO(IOError) (which forces every layer to explicitly rewrap; you can't have rethrows very often). Even if it did have ADTs, do you really want IOError | MemoryError | LoggingError | UnexpectedError | ...? Once you have a few layers, I wind up with layer upon layer of wrapping of some underlying "root cause" that have to be painfully unwrapped to deal with.

And how are you going to deal with it? In the overwhelming majority of cases, what do catch blocks look like?

} catch {
    logError(error)
    return
}

It is extremely uncommon for Cocoa programs (i.e. "apps") to dig deeply into the exact root cause of the error and perform different operations based on each precise case. There might be one or two cases that have a recovery, and the rest are things you couldn't do anything about anyway. (This is a common issue in Java with checked exception that aren't just Exception; it's not like no one has gone down this path before. I like Yegor Bugayenko's arguments for checked exceptions in Java which basically argues as his preferred Java practice exactly the Swift solution.)

This is not to say that there aren't cases where strongly typed errors would be extremely useful. But there are two answers to this: first, you're free to implement strongly typed errors on your own with an enum and get pretty good compiler enforcement. Not perfect (you still need a default catch outside the switch statement, but not inside), but pretty good if you follow some conventions on your own.

Second, if this use case turns out to be important (and it might), it is not difficult to add strongly typed errors later for those cases without breaking the common cases that want fairly generic error handling. They would just add syntax:

func something() throws MyError { }

And callers would have to treat that as a strong type.

Last of all, for strongly typed errors to be of much use, Foundation would need to throw them since it is the largest producer of errors in the system. (How often do you really create an NSError from scratch compared to deal with one generated by Foundation?) That would be a massive overhaul of Foundation and very hard to keep compatible with existing code and ObjC. So typed errors would need to be absolutely fantastic at solving very common Cocoa problems to be worth considering as the default behavior. It couldn't be just a little nicer (let alone have the problems described above).

So none of this is to say that untyped errors are the 100% perfect solution to error handling in all cases. But these arguments convinced me that it was the right way to go in Swift today.

14
  • "it is not difficult to add strongly typed errors later for those cases without breaking the common cases that want fairly generic error handling" There are Java projects where I wish they would do that...
    – GreenThor
    Commented Dec 1, 2016 at 8:12
  • 2
    I don't buy their opinion. Though SO is not a good platform for discussion... IMO, (1) Typed error might be bad for APIs, but very good for apps especially if I use error throwing as a flow control because I need predictable branching. (2) rethrow is bad. Higher level code usually cannot understand or handle lower level errors properly. Due to lack of context. All lower level errors need to be handled at mid-level and mid-level should produce a proper mid-level error for higher level code. Just rethrowing means just doing nothing for errors.
    – eonil
    Commented Apr 10, 2017 at 0:49
  • 1
    Even for APIs, I think providing a sort of classification using protocols or something would be better than nothing. I hope them to add error type check ASAP...
    – eonil
    Commented Apr 10, 2017 at 0:50
  • One of your arguments (maybe even your main argument) is that when an API adds error cases, it would break existing code and force the API consumer to deal with the new case. I think that it is actually a good thing. After updating the API, the compiler will tell me that I need to handle a new error case and will point me to the exact location where I need to handle it. Yes! I want that!
    – Lensflare
    Commented Feb 28, 2019 at 16:32
  • 1
    @Lensflare will point me to the exact location where I need to handle it: yes, that's precisely what I thought too. But I guess the argument is that most developers don't have the bandwidth to deal with new errors, and would therefore simply get frustrated when their code needs to be rebuilt (they'd rather just let existing code "somehow" handle any new errors, even if not quite perfectly). This in turn means that the library developers (who don't want frustrated users) would end up avoiding adding new error types, which is a bad outcome.
    – max
    Commented Dec 25, 2019 at 9:34
24

The choice is a deliberate design decision.

They did not want the situation where you don't need to declare exception throwing as in Objective-C, C++ and C# because that makes callers have to either assume all functions throw exceptions and include boilerplate to handle exceptions that might not happen, or to just ignore the possibility of exceptions. Neither of these are ideal and the second makes exceptions unusable except for the case when you want to terminate the program because you can't guarantee that every function in the call stack has correctly deallocated resources when the stack is unwound.

The other extreme is the idea you have advocated and that each type of exception thrown can be declared. Unfortunately, people seem to object to the consequence of this which is that you have large numbers of catch blocks so you can handle each type of exception. So, for instance, in Java, they will throw Exception reducing the situation to the same as we have in Swift or worse, they use unchecked exceptions so you can ignore the problem altogether. The GSON library is an example of the latter approach.

We chose to use unchecked exceptions to indicate a parsing failure. This is primarily done because usually the client can not recover from bad input, and hence forcing them to catch a checked exception results in sloppy code in the catch() block.

https://github.com/google/gson/blob/master/GsonDesignDocument.md

That is an egregiously bad decision. "Hi, you can't be trusted to do your own error handling, so your application should crash instead".

Personally, I think Swift gets the balance about right. You have to handle errors, but you don't have to write reams of catch statements to do it. If they went any further, people would find ways to subvert the mechanism.

The full rationale for the design decision is at https://github.com/apple/swift/blob/master/docs/ErrorHandlingRationale.rst

EDIT

There seems to be some people having problems with some of the things I have said. So here is an explanation.

There are two broad categories of reasons why a program might throw an exception.

  • unexpected conditions in the environment external to the program such as an IO error on a file or malformed data. These are errors that the application can usually handle, for example by reporting the error to the user and allowing them to choose a different course of action.
  • Errors in programming such as null pointer or array bound errors. The proper way to fix these is for the programmer to make a code change.

The second type of error should not, in general be caught, because they indicate a false assumption about the environment that could mean the program's data is corrupt. There my be no way to continue safely, so you have to abort.

The first type of error usually can be recovered, but in order to recover safely, every stack frame has to be unwound correctly which means that the function corresponding to each stack frame must be aware that the functions it calls may throw an exception and take steps to ensure that everything gets cleaned up consistently if an exception is thrown, with, for example, a finally block or equivalent. If the compiler doesn't provide support for telling the programmer they have forgotten to plan for exceptions, the programmer won't always plan for exceptions and will write code that leaks resources or leaves data in an inconsistent state.

The reason why the gson attitude is so appalling is because they are saying you can't recover from a parse error (actually, worse, they are telling you that you lack the skills to recover from a parse error). That is a ridiculous thing to assert, people attempt to parse invalid JSON files all the time. Is it a good thing that my program crashes if somebody selects an XML file by mistake? No isn't. It should report the problem and ask them to select a different file.

And the gson thing was, by the way, just an example of why using unchecked exceptions for errors you can recover from is bad. If I do want to recover from somebody selecting an XML file, I need to catch Java runtime exceptions, but which ones? Well I could look in the Gson docs to find out, assuming they are correct and up to date. If they had gone with checked exceptions, the API would tell me which exceptions to expect and the compiler would tell me if I don't handle them.

24
  • 8
    The thing is, a very popular pattern in Swift is to use enumerations as error types. This allows us to define a single type of error that a function can throw, but has multiple cases that describe exactly what went wrong, with additional information with each case if necessary. This fact pretty much combats the argument of "you'll be forced to write out tons of catch blocks", as enforcing that a function throws a single enumeration type still allows you to just write a single catch block. Personally I think the added safety of allowing throws to be type-annotated far outweighs any drawbacks.
    – Hamish
    Commented Nov 21, 2016 at 14:44
  • 7
    ...because that makes callers have to either assume all functions throw exceptions and include boilerplate to handle exceptions that might not happen, or to just ignore the possibility of exceptions -- Neither of these assertions is true. Every properly-written C# program has a backstop try/catch handler somewhere near the top of the call stack that prevents the program from crashing if an unhandled exception occurs anywhere in the framework and logs the exception. The developer can then decide what to do about those unhandled exceptions that actually occur in practice. Commented Nov 21, 2016 at 18:53
  • 4
    @JeremyP: There is always the possibility of an exception being thrown, unless you're using something like TryParse(), perhaps even then. I don't see how providing a backstop exception handler could be categorized as ignoring that possibility. Commented Nov 21, 2016 at 19:56
  • 6
    quote paragraph: <<(... gson ...) "That is an egregiously bad decision. "Hi, you can't be trusted to do your own error handling, so your application should crash instead".>> It's actually the only sane decision, and shows quite some misunderstanding on your part, IMHO. More importantly, it seems quite contentious, and also doesn't add anything to the otherwise very good answer. I'd remove it. YMMV.
    – Martin Ba
    Commented Nov 21, 2016 at 20:04
  • 8
    That is an egregiously bad decision. That is entirely your opinion and it is most unwelcomed. You may disagree with the design choice, but, quite obviously, other people think it's a good idea to do that. Calling their work "egregiously bad" is not ok in my book, and very disrespectful.
    – Tunaki
    Commented Nov 21, 2016 at 20:49
4

✅ Swift 6 Typed Throws

You can define a function that only throws a custom type i.e. CatError like:

func callCat() throws(CatError) -> Cat { ... }

and catch it later like:

do {
  try callCat()
} catch {
   // `error` is of type `CatError` (In Swift 5, it was `any Error`)
}

💡 More info

Note that When a do statement can throw errors with different concrete types, or involves any calls to functions using untyped throws, the catch block will receive a thrown error type of an any Error like before in Swift 5.

do {
  try callCat()
  try callDogs()
} catch {
  // `error` has type 'any Error', as it was in Swift 5 because of multiple throwing error types inside the do block
}

The caught error type for a do..catch statement will be inferred from the various throwing sites within the body of the do block. One can explicitly specify this type with a throws clause on do block itself, i.e.,

do throws(CatError) {
  try callCat()
} catch let myError {
   // myError is of type CatError
}

🌐 Here is full detailed information about Typed Throws in Swift.

1
  • 1
    🎊This is now possible with Swift 6.0 (XCode 16.0)
    – ambassador
    Commented Sep 26, 2024 at 11:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.