2015-11-01 61 views
3

看到此错误:为什么Swift看起来“深入”我的错误处理?

enum MyError: ErrorType { 
    case Foo 
    case Bar 
} 

func couldThrow(string: String) throws { 
    if string == "foo" { 
     throw MyError.Foo 
    } else if string == "bar" { 
     throw MyError.Bar 
    } 
} 

func asdf() { 
    do { 
     //Error: Errors thrown from here are not handled 
     //because the enclosing catch is not exhaustive. 
     try couldThrow("foo") 
    } catch MyError.Foo { 
     print("foo") 
    } catch MyError.Bar { 
     print("bar") 
    } 
} 

然而,我catch ES涵盖所有的可能性。为什么Swift不会“深入”地分析所有可能性并告诉我什么是错的?

例如,搜索“抓VendingMachineError.InvalidSelection”在这里:https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508

你会看到在那里,苹果正在做我的方式。他们的代码错了吗?

回答

4

编译器很难确切知道一段代码可能导致哪些异常,因为任何在更深层次上未处理的异常都会被传播。虽然你的情况相对简单,但这通常是一个非常困难的问题。

注意无处功能的代码说哪个例外它可以抛出,只知道它可以扔东西......

关键语句:

For example, the following code handles all three cases of the VendingMachineError enumeration, but all other errors have to be handled by its surrounding scope

所以,在他们的榜样,但他们不” t显示它,那段代码的容器也必须能够投掷。这是因为它不处理所有可能的例外情况。

对于你的情况,asdf需要定义throws或它需要一个捕获所有。

1

虽然Wain的答案是正确的,但还有另一种消除错误的方法:使用try!将任何未处理的错误视为致命的运行时错误。

func asdf() { 
    try! { 
     do { 
      //Error: Errors thrown from here are not handled 
      //because the enclosing catch is not exhaustive. 
      try couldThrow("foo") 
     } catch MyError.Foo { 
      print("foo") 
     } catch MyError.Bar { 
      print("bar") 
     } 
    }() 
} 
相关问题