Catch “IndexOutOfBoundsException” in Swift 2

前端 未结 2 1661
一个人的身影
一个人的身影 2020-12-19 19:21

I got this code in my Playground:

func throwsError() throws{
    var x = [1,2]
    print(x[3])
}

func start(){

    do{
        try throwsError()

    }
            


        
2条回答
  •  误落风尘
    2020-12-19 20:14

    In Swift, you can't catch anything. You can only catch errors thrown with the throw statement in other Swift code or errors, of type NSError set by called Objective C code.

    The default array subscript raises an exception, but does not throw a Swift error, so you cannot use try/catch with it.

    See also this article by Erica Sadun.

提交回复
热议问题