2015-11-01 34 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") 
     } 
    }() 
} 
相關問題