我正在尝试使用swift 2.1进行错误处理,
下面的场景,
var test: NSArray! = ["Test1", "Test2"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do{
try testing()
} catch {
print("error")
}
}
func testing() throws {
print(test.objectAtIndex(7))
}
在上面的例子中,我的应用程序崩溃了,即以NSException类型的意外异常终止,但是我希望控件应该在Catch块中,而不是崩溃。
我能知道解决办法吗。有人能帮我解决这个问题吗
最佳答案
唯一可行的方法就是抛出错误(正如Eric D.在评论中指出的那样):
游乐场:
enum ArrayError : ErrorType{
case OutOfBounds
}
class SomeClass {
var test: NSArray! = ["Test1", "Test2"]
func testCode() {
do{
try testing(3)
} catch let error{
print("error = \(error)") // for index 3 this would print "error = OutOfBounds\n"
}
}
func testing(index: Int) throws -> String {
guard index < test.count else{
throw ArrayError.OutOfBounds
}
return test[index] as! String
}
}
let sC = SomeClass()
sC.testCode()
关于ios - iOS Swift 2.1-使用Try Catch进行错误处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35940120/