Im a c# developer so i very used to wrapping a whole block of code in a try catch, writing to the event log and then not worrying about it.
i just can't get my head round the catch in swift
Im using the Kanna HTML/XML pod to parse a html page and look for links inside a table and extract them. Im doing it like this
enum MyError: Error {
case FoundNil(String)
}
if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8)
{
var count = 0
//loop through all instances of <tr> in the html
for row in doc.xpath("//tr") {
var linkName = ""
do{
//get the <a> text from inside a <div> from the 2nd <td>
if let name = row?.xpath("//td[2]//div//a[1]")[count]
{
linkName = name.text
}
else{
throw MyError.FoundNil("name")
}
count = count + 1
}
catch{
print("Error: \(error)")
}
}
}
The trouble is i don't always know that there will be a link in the table cell at xpath //td[2]//div//a[1] so it works for the first few rows then it crashes out with a fatal error,
fatal error: Index out of range
it doesn't go to the catch or the else
I've also tried using guard but that doesn't throw either
guard let name = row?.xpath("//td[2]//div//a[1]")[count] else{
throw MyError.FoundNil("name")
}
and what if i needed to check 50 table cells would i need a try catch on all of them