3

How could a function throw multiple exceptions? For instance in Java would be something like this:

private Int f(Int data, boolean e)
        throws AException, BException,
        CException {...

Thanks

Viker
  • 3,183
  • 2
  • 25
  • 25
  • 2
    Did you have a look at the "Error handling" chapter in the Swift reference? In Swift, it is just `func f(...) throws` and you do not (and can not!) specify *which* errors are thrown. – Martin R Mar 31 '17 at 10:48
  • I think you can specify it in this way: func f() throws -> YourExceptionType , but only one exception type, I was wondering how to throw multiple. – Viker Mar 31 '17 at 11:44
  • No you cannot specify it that way. Where did you get that from? – Martin R Mar 31 '17 at 11:51
  • @user23 What you're specifying there is the *return* type of the function, which is unrelated to the possible error types that the function can `throw`. In Swift, a throwing function can throw *any* error type that conforms to the `Error` protocol – there's no way to specify specific type(s) of error that can be thrown. – Hamish Mar 31 '17 at 11:53
  • There was an interesting discussion on why Swift doesn't support being able to specify the type(s) of error that a function can throw here: [Why is 'throws' not type safe in Swift?](http://stackoverflow.com/q/40718542/2976878) – Hamish Mar 31 '17 at 11:55

1 Answers1

4

The language does not supports that, most likely because it is considered an anti-pattern. However with a bit of ingenuity you can have an error case that takes an array of errors:

enum MyError: Error {
    case general
    case notFound
    case invalid
    case multiple([MyError])
}

func test() throws {
    throw MyError.multiple([.general, .invalid])
}
cescofry
  • 3,706
  • 3
  • 26
  • 22