override func viewdidload()
//丟擲錯誤
// throw vendingmachineerror.insufficientfunds(coinsneeded: 5)
//2. 處理錯誤
//swift 中有四種方式處理錯誤:
//1. 將錯誤從乙個函式傳播(propagate)到呼叫它的**
//2. 用 do-catch 語句
//3. 將錯誤作為可選值
//4. 斷言錯誤不會發生
//在會丟擲錯誤的方法前加 try, try? , try!
//3. 使用丟擲函式傳播(propagating)錯誤
struct item
class vendingmachine
guard item.count > 0 else
guard item.price <= coinsdeposited else
coinsdeposited -= item.price
var newitem = item
newitem.count -= 1
inventory[name] = newitem
print("dispensing \(name)")}}
//4. do-catch
var vendingmachine = vendingmachine()
vendingmachine.coinsdeposited = 8
do catch vendingmachineerror.invalidselection catch vendingmachineerror.outofstock catch vendingmachineerror.insufficientfunds(let coinsneeded) catch
// prints "insufficient funds. please insert an additional 2 coins."
//5. 錯誤轉為可選值
func somethrowingfunction() throws -> int
let x = try? somethrowingfunction()
let y: int?
do catch
//6. 阻止錯誤傳播
//確定不會出錯時,用 try!
//載入應用內的不會出錯
//7. 特定清理行為
func processfile(filename: string) throws
while let line = try file.readline()
// close(file) is called here, at the end of the scope.}}
}
Swift 錯誤處理
宣告列舉錯誤型別 enum printererror error 捕捉異常的五種方式 1.使用throw 來丟擲乙個錯誤 func send job int,printername string throws string return job sent 2.do catch 在 塊中執行操作,do...
Swift 錯誤處理專題
playground noun a place where people can play import uikit 下面的三個用於除錯,在真機上不起作用 assert 1 0 必須滿足括號裡面的邏輯,不然停止 assert 1 0,error 必須滿足括號裡面的邏輯,不然停止並報錯 asserti...
swift 中錯誤處理
enum customerror error 定義乙個測試用的類 class testerrorclass name s func showstring 第一種使用方式,執行 後,直接丟擲異常,中止執行 let tes trytesterrorclass s 執行結果 lldb expr 123.c...