Catch “IndexOutOfBoundsException” in Swift 2

2019-01-26 20:22发布

问题:

I got this code in my Playground:

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

func start(){

    do{
        try throwsError()

    }
    catch let unknown{
        "unknown: \(unknown)"
    }
}

start()

So obviously the'throwsError function throws an error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION

Is there a way to catch this? I read online to write a subscript for the Array class that always checks for range but the issue is bigger: Am I not capable to just catch anything?

回答1:

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.



回答2:

You can write your own method. Not really elegant, but works.

enum ArrayError: ErrorType {
    case OutOfBounds(min: Int, max: Int)
}

extension Array {

    mutating func safeAssign(index:Int, value: Element) throws {

        guard self.count > index && index >= 0 else {
            throw ArrayError.OutOfBounds(min: 0, max: (self.count - 1))
        }

        self[index] = value

    }
}

var myArray : [Float] = [1,2]

do {
    try myArray.safeAssign(1, value: Float(5))
} catch ArrayError.OutOfBounds(let min, let max) {
    print("out of bounds : \(min) => \(max)")
}