0

with swift3 and I want handling one error,

public func titulo()
        {do{
            marca.snippet=address_components?[1].short_name
            marca.title = try (address_components?[2].short_name)!+" "+(address_components?[3].short_name)!
            //return titulo
        }catch{
            marca.title="sin titulo"
            }

    }

Error call when address_components is nil , but in the debug:

enter image description here

What I can do , to fix this?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Daniel ORTIZ
  • 2,488
  • 3
  • 21
  • 41
  • 1
    Related: [How do I catch “Index out of range” in Swift?](http://stackoverflow.com/questions/37222811/how-do-i-catch-index-out-of-range-in-swift). The answer is simply you do not catch the runtime error – you prevent it from happening in the first place (i.e [by *safely* unwrapping the optional](http://stackoverflow.com/q/32170456/2976878) and by not indexing out of a collection's bounds). – Hamish Mar 24 '17 at 22:00

2 Answers2

2

try / catch doesn't catch exceptions, only errors thrown. It does nothing to help you avoid crashing when using implicitly unwrapped optionals (!). The warning was a good hint here.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
2

You have two things going on here: 1) the try/catch, and 2) force-unwrapping of an optional.

Update: The try/catch is fine. The code you have inside the try/catch actually doesn't throw. Therefore, you don't need the try/catch there.

An example of something that does throw is FileManager.contentsOfDirectory. It looks like this in Apple's documentation (notice the throws keyword):

func contentsOfDirectory(at url: URL, 
includingPropertiesForKeys keys: [URLResourceKey]?, 
             options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]

You can make your own functions throw as well, but your current code doesn't. That's why you get the 'catch' block is unreachable... message.

The second issue is with the optionals.

An "optional" in Swift is something that could possibly be nil (empty, without a value).

Your code has these two parts: (address_components?[2].short_name)! and (address_components?[3].short_name)!

The ! marks are saying that you're CERTAIN that these items won't be nil! (Think of the ! as telling the system "YES! IT'S NOT NIL!" Likewise, think of the ? as saying, "Umm, is this empty? Does this have a value?")

As it turns out, one of those values IS nil. Therefore, Swift doesn't know what the heck to do with it. CRASH AND BURN! ;)

So, in addition to your try/catch, you're going to need some guard statements or if let statements somewhere to make sure your values are not nil.

leanne
  • 7,940
  • 48
  • 77
  • 1
    No, the `do/catch` is not fine since the code inside the `try` doesn't throw. – rmaddy Mar 24 '17 at 22:25
  • And a better description of `!` is "crash if nil". Swift knows just what to do when you are sure it's not nil but wrong. – rmaddy Mar 24 '17 at 22:27