如何在 EXC_BAD_INSTRUCTION 上设置例外?

How can i put an exception on EXC_BAD_INSTRUCTION?

我正在尝试为以下行设置一个例外:

let someData Int = Int(anArray[0])!

我想要异常,以便在它是字符串而不是整数时忽略它。

我是 swift 的新手,但在 python 中我可以执行以下操作:

try:
    let someData Int = Int(anArray[0])!
except:
    pass

我试过以下方法:

guard let someData Int = Int(anArray[0])! else {
    print("error")
}

,

let someData Int = try! Int(anArray[0])!

我正在使用 swift 3

您错过了正确的解决方案:

if let someData = Int(anArray[0]) {
    // someData is a valid Int
}

或者您可以使用 guard:

guard let someData = Int(anArray[0]) else {
    return // not valid
}

// Use someData here

请注意完全没有使用 !。除非你知道它不会失败,否则不要强行解包选项。

在 Swift 中,try-catch 块如下所示:

do {
    //call a throwable function, such as 
    try JSONSerialization.data(withJSONObject: data)
} catch {
    //handle error
}

但是,您只能捕获来自 throwable 函数的错误,这些函数在文档中始终标有 throws 关键字。 try 关键字只能用于可抛出的函数,而 do-catch 块只有在 do 块中使用 try 关键字时才有效。

您无法捕获其他类型的异常,例如您试图捕获的强制 casting/unwrapping 异常。

如果要使用可选绑定,处理可选值的正确方法。

guard let someData = Int(anArray[0]) else {
    print("error")
    return //bear in mind that the else of a guard statement has to exit the scope
}

如果您不想退出范围:

if let someData = Int(anArray[0]) {
    //use the integer
} else {
    //not an integer, handle the issue gracefully
}