[swift-evolution] throws!

Stephen Canon scanon at apple.com
Mon Dec 7 10:13:46 CST 2015


> On Dec 7, 2015, at 5:12 AM, Adrian Kashivskyy via swift-evolution <swift-evolution at swift.org> wrote:
> 
> This seems like reasonable feature for me. Combined with throwing subscripts (proposed in another thread), we could translate that into bounds checking as well:
> 
>> let array = [1, 2, 3]
>> 
>> let fifth = array[5] // traps
>> 
>> let fifth = try? array[5] // nil
> 
> However, I'm still trying to find a use case for catching such errors. Imagine you're making a GUI app (e.g. for iOS), and then write the following code:
> 
>> do {
>> 	let fifth = try array[5]
>> } catch BoundsError {
>> 	// ???
>> }
> 
> or
> 
>> let sum: Int = Int.max // assuming it has the max value by accident
>> 
>> do {
>> 	sum += 1
>> } catch ArithmeticError {
>> 	// ???
>> }
> 
> What would you do in the catch clause?

There’s a common scenario where there are multiple algorithms that might be used to perform a computation:

	do {
		// fast algorithm that is usually correct by may overflow on rare inputs
	} catch ArithmeticError {
		// slow algorithm that can give correct result no matter what
	}

Note that it’s often *faster* to structure the computation this way than it is to try to inspect the inputs to ascertain whether or not the slow algorithm needs to be used before doing the work.

– Steve


More information about the swift-evolution mailing list