Why Is 'Throws' Not Type Safe in Swift

Why is 'throws' not type safe in Swift?

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.

Invalid conversion from throwing function of type '(_) throws - ()' to non-throwing function type '(DataSnapshot) - Void'

You are throwing an error in the completion block. This is not possible and causes the error.

The return value of the closure is not related to the return value of the enclosing function – strictly spoken throws is not a return value but is affected, too.

To be able to return something from the closure you have to implement a completion block rather than throws

func getUserList(completion : (Error?) -> ())

and use it

completion(value.isEmpty ? UserError.Empty : nil)

Side-note: You are using too many question and exclamation marks. Use optional binding to unwrap optionals for example (and use Swift native collection types)

if let value = snapshot.value as? [String:Any] {
for key in value.keys { ...

Swift 2: Invalid conversion from throwing function of type to non-throwing function

This was fast. I have figured the solution for my problem out with a little help of this article:

http://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

you have to put a general catch clause at the end of the code because the catch of NSError alone is not sufficient.

catch let error as NSError
{
failure(error: error)
return
}

// this is important -->
catch
{
}

Simplest way to throw an error/exception with a custom message in Swift?

The simplest approach is probably to define one custom enum with just one case that has a String attached to it:

enum MyError: ErrorType {
case runtimeError(String)
}

Or, as of Swift 4:

enum MyError: Error {
case runtimeError(String)
}

Example usage would be something like:

func someFunction() throws {
throw MyError.runtimeError("some message")
}
do {
try someFunction()
} catch MyError.runtimeError(let errorMessage) {
print(errorMessage)
}

If you wish to use existing Error types, the most general one would be an NSError, and you could make a factory method to create and throw one with a custom message.



Related Topics



Leave a reply



Submit