8

I'm new to Swift and I have a little problem.

I have a piece of code, and any line could potentially throw an error.

My problem is, I don't want to go through line by line catching each error, I want to catch them all in one statement.

In python you can do this

try:
    exampleArray = [1,2,3,4]
    print(exampleArray[4])
except Exception as e:
    print(e)
    pass

What that does is try to print a value from the array that doesn't exist, but it is caught by the except statement, I am wondering whether something this easy exists in Swift

To clarify, I am not trying to catch an index out of range error, I just want to catch an error, no matter what it is.

Is it possible without declaring my own errors, and throwing them line by line?

Will
  • 4,942
  • 2
  • 22
  • 47

1 Answers1

1

In Swift you can only catch errors that are thrown.

Since not all errors are handled by throwing (e.g. an out-of-range array access), you cannot catch everything.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Wouldn't catch be unreachable because of no throw in do? – Will Feb 18 '17 at 23:26
  • @Will If that's the case, yes. The `catch` body is only entered if an error is thrown. – Emil Laine Feb 18 '17 at 23:27
  • Yes, just tested and this does not work, if an error occurs in do, app crashes – Will Feb 18 '17 at 23:27
  • `catch` only catches _thrown_ errors, not arbitrary programming errors in the code. Since an out-of-range array access does not `throw` anything, you can't `catch` it. – Emil Laine Feb 18 '17 at 23:29
  • The out of range error won't happen, it was an example to show an error – Will Feb 18 '17 at 23:30
  • @SilentDownvoters: Is there something incorrect in the answer? – Emil Laine Feb 18 '17 at 23:34
  • 4
    Maybe you misunderstood the question. But it is about catching absolutely all and any error inside the block. Your answer fails to do that. Actually, real answer is Swift is not capable of catching all exceptions like some other languages do. – Dalija Prasnikar Feb 18 '17 at 23:39