error handling
9593 ワード
Error Handling - The Swift Programming Language (Swift 5.6)
throwsを作成する場所:矢印の前 enum Errorプロトコル を使用エラー を投げ出す関数のthrows→関数内部でthrowsを教える tryの後にthrows関数 を作成
関数が内部でthrows関数を呼び出す場合は、throwsを記述する必要があります.最終エラー処理
You use
throwsを作成する場所:矢印の前
func canThrowErrors() throws -> String
実施方法関数が内部でthrows関数を呼び出す場合は、throwsを記述する必要があります.
do catch
文enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
class VendingMachine {
. . .
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
. . .
}
}
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vendingMachine.vend(itemNamed: snackName)
}
catch文に条件を表示するdo {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
} catch pattern 3, pattern 4 where condition {
statements
} catch {
statements
}
func eat(item: String) throws {
do {
try vendingMachine.vend(itemNamed: item)
} catch VendingMachineError.invalidSelection, VendingMachineError.insufficientFunds, VendingMachineError.outOfStock {
print("Invalid selection, out of stock, or not enough money.")
}
}
try?You use
try?
to handle an error by converting it to an optional value. If an error is thrown while evaluating the try?
expression, the value of the expression is nil
.func someThrowingFunction() throws -> Int {
// ...
}
let x = try? someThrowingFunction()
let y: Int?
do {
y = try someThrowingFunction()
} catch {
y = nil
}
Reference
この問題について(error handling), 我々は、より多くの情報をここで見つけました https://velog.io/@tiana/error-handlingテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol