尝试在Swift中捕获

时间:2016-10-05 09:56:30

标签: swift try-catch

我是一个c#开发人员所以我非常习惯在try catch中包装整个代码块,写入事件日志然后不用担心它。

我只是不能快速地抓住我的头脑。

我使用Kanna HTML / XML窗格来解析html页面并查找表格中的链接并将其解压缩。我是这样做的

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)")

        }
    }
}

麻烦的是我不知道在xpath // td [2] // div // a [1]的表格单元格中会有一个链接,所以它适用于前几行然后它因致命错误而崩溃,

  

致命错误:索引超出范围

它没有去捕获或其他

我也曾尝试使用后卫,但不会抛出

guard let name =  row?.xpath("//td[2]//div//a[1]")[count] else{
    throw MyError.FoundNil("name")
}

如果我需要检查50个表格单元格怎么办? 我是否需要尝试捕捉所有这些

3 个答案:

答案 0 :(得分:0)

如评论中所述,您无法捕获运行时异常。

但您可以使用可选绑定并在一行中检查有效范围

if let name = row?.xpath("//td[2]//div//a[1]") where count < name.count {
  linkName = name[count].text
}

在Swift 3中用逗号替换where

答案 1 :(得分:0)

我的回答只是指尝试......捕捉......也许它也可以为其他人工作。你可以这样做......

enum MyError: Error {
    case FoundNil(String)
}
do{
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 = ""

            //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)")

        }

你仍然需要任何帮助随时问我。

答案 2 :(得分:0)

最后我刚拿出所有的捕获量并重新设计了我如何访问数据并且它似乎已经完成了这个技巧 我不再使用count来遍历行,使用不同的xpath值,然后直接在活动行上工作,而不是我认为我在数组中,我认为它只是。在xpath的开头,它全部排序,就像在当前行上工作所以我不需要[count]来到它

let xpo = doc.xpath("//tr") as XPathObject
let xCount = xpo.count
var count = 0 
for row in xpo {
    if (count <= xCount){
        var linkName = ""

        for a in row.xpath(".//td[2]//div//a[1]")
        {
            linkName =  a.text
        }
    }
    count = count +1 
}