0
func errorFunction()
{
    do
    {
        let arrayOfInts: [Int] = [1, 2, 3]

        let i:Int = arrayOfInts[5]
        print(i)
    }
    catch
    {
        print(error)
    }

}

At the line where catch is written, it gives me warning 'catch' block is unreachable because no errors are thrown in 'do' block. However, as you can see, the code is going to throw Index out of bounds error. Also, when I run this code, the code truly does not reach catch block.

How can I catch this error?

Please note that I do not want to catch this exception. Using array was just an example to demonstrate. The reason for asking this question is to understand how to use this catch block to catch this or similar exceptions.

PS

  1. If you find my question too naive, please feel free to down-vote - but do give an answer for it - I'm really looking for one.
prabodhprakash
  • 3,825
  • 24
  • 48
  • 1
    http://ericasadun.com/2015/06/09/swift-why-try-and-catch-dont-work-the-way-you-expect/ – Bhavin Bhadani Jan 17 '17 at 08:37
  • http://stackoverflow.com/a/32358759/4601170 – Bhavin Bhadani Jan 17 '17 at 08:37
  • I don't want to save this crash - Array was just an example. I want this runtime error to come and get caught in catch block. – prabodhprakash Jan 17 '17 at 08:38
  • 1
    See also http://stackoverflow.com/questions/38737880/uncaught-error-exception-handling-in-swift: *"Swift has no mechanism to catch all arbitrary runtime exceptions."* – Martin R Jan 17 '17 at 08:40
  • 1
    @prabodhprakash You can't catch anything that isn't marked with `throws`. And almost everything marked with `throws` has to be handled in some way or another, using `do...catch`, `try!` or `try?`. In other words, You can never stop a runtime error from happening using `do...catch` nor can you make a method that throws produce a runtime error. – Sweeper Jan 17 '17 at 08:44
  • 1
    You are mixing two completely different things. "Index out of bounds" is a *runtime exception* and cannot be `catch`ed. `try/catch` is used to catch *Swift errors* which are thrown with `throw`. – Martin R Jan 17 '17 at 08:45
  • Trying to catch a runtime exception is not the `swifty` way of doing things, just check if the array count is larger than the index you're trying to get, then handle your error accordingly. – Erik Terwan Jan 17 '17 at 08:54
  • Does it mean, there is absolutely no simple way to catch such runtime errors? – prabodhprakash Jan 17 '17 at 09:01
  • @prabodhprakash: Yes, that is what all the referenced answers tell. – Martin R Jan 17 '17 at 09:28

0 Answers0