17

When calling a function in Swift 3 that throws, you have to be exhaustive in catching all possible errors, which often means you have an unnecessary extra catch {} at the end to handle errors that won't happen.

Is it possible to say throws MyErrorType so that the compiler can know you have indeed been exhaustive when you handle all cases from that enumeration?

1

2 Answers 2

7

There's no simple way to be type-safe with thrown errors. Consider this, if the compiler allowed you to specify throws MyErrorType, then it would also have to ensure within that function body that you're not trying a function that could potentially throw a different type outside of a do/catch block. (Well there is but it would add layers of unnecessary complexity). The Swift compiler can already be slow and get stuck in loops when inferring types, inferring Thrown types all the way up a chain of throwing functions could be a nightmare.

The running idea is that for most errors you're going to handle them in a small subset of ways anyhow.

That being said, there's no need for you to add extra catch let error as MyErrorType clauses, you can simply use a switch in a catch block like so:

do {
  try something()
} catch let e {
  switch e {
  case let m as MyErrorType: handleMyError(m)
  case let o as OtherErrorType: handleOther(o)
  case is ThirdErrorType: print("error \(e)")
  default: handleElse(e)
  }
}
10
  • 1
    How did Java solve this problem without running into the problems that you mention the Swift compiler would run into? I've never heard that the implementation of checked exceptions in Java being either slow or complex. Commented Mar 8, 2022 at 14:28
  • @Feuermurmel Because Java will just allow an exception that isn't explicitly caught by type to be raised to the JVM. Swift will not, it is fully type-safe even for thrown errors, therefor if a function is to specify the type it throws, then any calling function must then ensure it catches errors that aren't of the type the caller can throw. Not only would this type checking get exponentially more complex on bigger projects, it would pretty much totally defeat the purpose of letting throwing functions call other throwing functions outside of do/catch blocks (you'd always have to use them)
    – apocolipse
    Commented Oct 5, 2023 at 19:54
  • What you're writing is nonsense. You say that type checking with typed errors gets exponentially more complex, without backing it up. Again, javac does this without this performance/complexity issue. You are mixing up Java, the language, (specified by the The Java® Language Specification) and the JVM, (specified by the The Java® Virtual Machine Specification) saying that the latter does not type-check checked exceptions does not mean that the former doesn't fully do so. Commented Oct 6, 2023 at 9:43
  • Also, there is now a Result type in Swift, which is equivalent to checked exceptions in their expressiveness. Solving the problem of type-checking code that uses Result is equivalent to solving the problem for typed errors, so the Swift compiler is obviously capable of doing that without the complexity issues that you mention. It can be done without global analysis. Also, a lot of other languages have similar Result types (e.g. Rust or Haskell) and they were also able to solve the complexity problems. Commented Oct 6, 2023 at 9:45
  • Good summary of why the Swift team decided against typed errors. Compiler performance or complexity is not mentioned: stackoverflow.com/a/40722962/402281 Commented Oct 6, 2023 at 11:22
6

My suggestion for this problem is instead of throwing an error return a Result type in your function. It would be something like this.

enum MyCustomError: Error {
    case genericError
}

func operationThatFails() -> Result<Response, MyCustomError> {
    guard requiredConsition() else {
        return .failure(.genericError)
    }
    return Response()
}

Then you can handle the error like this:

let result = operationThatFails()
switch result {
case .success(let value):
    // handle success
case .failure(let error):
    // handle error
}

This way your error is always type safe

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.