Error Handling


Representing and Throwing Errors

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated.

enum VendingMachineError: Error {
   case invalidSelection
   case insufficientFunds(coinsNeeded: Int)
   case outOfStock
}

 You use a throw statement to throw an error. 

// 여기는 throw이고 throw가 발생할수 있는함수에 표시할때는 throws

throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

Handling Errors

When an error is thrown, some surrounding piece of code must be responsible for handling the error.

There are four ways to handle errors in Swift. 1. You can propagate the error from a function to the code that calls that function,2. handle the error using a docatch statement, 3. handle the error as an optional value, or 4. assert that the error will not occur. Each approach is described in a section below.

When a function throws an error, it changes the flow of your program, so it’s important that you can quickly identify places in your code that can throw errors. To identify these places in your code, write the try keyword—or the try? or try! variation—before a piece of code that calls a function, method, or initializer that can throw an error. These keywords are described in the sections below.

Propagating Errors Using Throwing Functions

To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function’s declaration after its parameters. A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow (->).

// 여기는 throws이고 결과로 throw를 발생시킬때는 throw 

func canThrowErrors() throws -> String
func cannotThrowErrors() -> String

A throwing function propagates errors that are thrown inside of it to the scope from which it’s called.

NOTE

Only throwing functions can propagate errors. Any errors thrown inside a nonthrowing function must be handled inside the function.

(함수에 throws가 표시되있지 않은 경우 상부로 propagate할수 없고 그 안에서 처리해야 한다는 의미)

struct Item {
   var price: Int
   var count: Int
}
class VendingMachine {
   var inventory = [
       "Candy Bar": Item(price: 12, count: 7),
       "Chips": Item(price: 10, count: 4),
       "Pretzels": Item(price: 7, count: 11)
   ]
   var coinsDeposited = 0
   
   func vend(itemNamed name: String) throws {

       // 참고 guard 구문 https://ericcerney.com/swift-guard-statement/

      // guard는 조건이 만족되지 않을 경우 else{} 안의 내용이 실행된다.
       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)
       }
       
       coinsDeposited -= item.price
       
       var newItem = item
       newItem.count -= 1
       inventory[name] = newItem
       
       print(“Dispensing (name)”)
   }
}

Because the vend(itemNamed:) method propagates any errors it throws, any code that calls this method must either handle the errors—using a docatch statement, try?, or try!—or continue to propagate them. For example, the buyFavoriteSnack(person:vendingMachine:) in the example below is also a throwing function, and any errors that the vend(itemNamed:) method throws will propagate up to the point where the buyFavoriteSnack(person:vendingMachine:) function is called.

let favoriteSnacks = [
   "Alice": “Chips”,
   "Bob": “Licorice”,
   "Eve": “Pretzels”,
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {

   // 

The nil-coalescing operator a ?? b is a shortcut for a != nil ? a! : b

   let snackName = favoriteSnacks[person] ?? “Candy Bar”
   try vendingMachine.vend(itemNamed: snackName)
}

In this example, the buyFavoriteSnack(person: vendingMachine:) function looks up a given person’s favorite snack and tries to buy it for them by calling the vend(itemNamed:) method. Because the vend(itemNamed:)method can throw an error, it’s called with the try keyword in front of it.

Throwing initializers can propagate errors in the same way as throwing functions. For example, the initializer for the PurchasedSnack structure in the listing below calls a throwing function as part of the initialization process, and it handles any errors that it encounters by propagating them to its caller.

struct PurchasedSnack {
   let name: String
   init(name: String, vendingMachine: VendingMachine) throws {
       try vendingMachine.vend(itemNamed: name)
       self.name = name
   }
}

Handling Errors Using Do-Catch

You use a docatch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.

Here is the general form of a docatch statement:

do {
   try expression
   statements
} catch pattern 1 {
   statements
} catch pattern 2 where condition {
   statements
}

You write a pattern after catch to indicate what errors that clause can handle. If a catch clause doesn’t have a pattern, the clause matches any error and binds the error to a local constant named error. For more information about pattern matching, see Patterns.

The catch clauses don’t have to handle every possible error that the code in its do clause can throw. If none of the catch clauses handle the error, the error propagates to the surrounding scope. However, the error must be handled by some surrounding scope—either by an enclosing docatch clause that handles the error or by being inside a throwing function. 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:

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
   try buyFavoriteSnack(person: “Alice”, vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
   print(“Invalid Selection.”)
} catch VendingMachineError.outOfStock {
   print(“Out of Stock.”)
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
   print(“Insufficient funds. Please insert an additional (coinsNeeded) coins.”)
}
// Prints “Insufficient funds. Please insert an additional 2 coins.”

Converting Errors to Optional Values

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. (try 바로 뒤에 따라오는 함수 수행중에 error가 발생하면 optional 변수건 상수건 nil을 저장하고 수행중 error없이 수행이 마무리되면 함수에서 return 된 값을 저장한다. 이후에 nil인지 아닌지 확인하고 그에 맞는 작업을 수행 하면 된다.)

func someThrowingFunction() throws -> Int {
   // …
}
let x = try? someThrowingFunction()

// 결국 위의 예시와 같은 내용
let y: Int?
do {
   y = try someThrowingFunction()
} catch {
   y = nil
}

If someThrowingFunction() throws an error, the value of x and y is nil. Otherwise, the value of x and y is the value that the function returned. 

func fetchData() -> Data? {
   if let data = try? fetchDataFromDisk() { return data }
   if let data = try? fetchDataFromServer() { return data }
   return nil
}

Disabling Error Propagation

Sometimes you know a throwing function or method won’t, in fact, throw an error at runtime. On those occasions, you can write try! before the expression to disable error propagation and wrap the call in a runtime assertion that no error will be thrown. If an error actually is thrown, you’ll get a runtime error.

(runtime에서 error가 발생하지 않을 것을 확신하는 경우 try!를 통해 error propagation를 막을 수 있다. )

let photo = try! loadImage(atPath: “./Resources/John Appleseed.jpg”)

Specifying Cleanup Actions

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. This statement lets you do any necessary cleanup that should be performed regardless of how execution leaves the current block of code—whether it leaves because an error was thrown or because of a statement such as return or break. For example, you can use a defer statement to ensure that file descriptors are closed and manually allocated memory is freed.(defer구문은 현재 블럭의 코드가 다수행 되면 수행된다. error가 발생하던 아니던 수행하게 된다.)

A defer statement defers execution until the current scope is exited. This statement consists of the defer keyword and the statements to be executed later. The deferred statements may not contain any code that would transfer control out of the statements, such as a break or a return statement, or by throwing an error. Deferred actions are executed in the reverse of the order that they’re written in your source code. That is, the code in the first defer statement executes last, the code in the second defer statement executes second to last, and so on. The last defer statement in source code order executes first.

func processFile(filename: String) throws {
   if exists(filename) {
       let file = open(filename)
       defer {
           close(file)
       }
       while let line = try file.readline() {
           // Work with the file.
       }
       // close(file) is called here, at the end of the scope.
   }
}

NOTE

You can use a defer statement even when no error handling code is involved.

Error Handling


Representing and Throwing Errors

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated.

enum VendingMachineError: Error {
   case invalidSelection
   case insufficientFunds(coinsNeeded: Int)
   case outOfStock
}

 You use a throw statement to throw an error. 

throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

Static vs class functions/variables in Swift classes?

Static vs class functions/variables in Swift classes?

Deinitialization

A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how initializers are written with the init keyword. Deinitializers are only available on class types. (structure,enumeration 은 해당없음)

How Deinitialization Works

Swift automatically deallocates your instances when they are no longer needed, to free up resources. Swift handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting.

Class definitions can have at most one deinitializer per class. The deinitializer does not take any parameters and is written without parentheses:

deinit {
   // perform the deinitialization
}

Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Because an instance is not deallocated until after its deinitializer is called, a deinitializer can access all properties of the instance it is called on and can modify its behavior based on those properties (such as looking up the name of a file that needs to be closed).

Deinitializers in Action

(참고 : static function in swift https://stackoverflow.com/a/29636742 )

class Bank {
   static var coinsInBank = 10_000
   static func distribute(coins numberOfCoinsRequested: Int) -> Int {
       let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
       coinsInBank -= numberOfCoinsToVend
       return numberOfCoinsToVend
   }
   static func receive(coins: Int) {
       coinsInBank += coins
   }
}

class Player {
   var coinsInPurse: Int
   init(coins: Int) {
       coinsInPurse = Bank.distribute(coins: coins)
   }
   func win(coins: Int) {
       coinsInPurse += Bank.distribute(coins: coins)
   }
   deinit {
       Bank.receive(coins: coinsInPurse)
   }
}

var playerOne: Player? = Player(coins: 100)
print(“A new player has joined the game with (playerOne!.coinsInPurse) coins”)
// Prints “A new player has joined the game with 100 coins”
print(“There are now (Bank.coinsInBank) coins left in the bank”)
// Prints “There are now 9900 coins left in the bank”

playerOne!.win(coins: 2_000)
print(“PlayerOne won 2000 coins & now has (playerOne!.coinsInPurse) coins”)
// Prints “PlayerOne won 2000 coins & now has 2100 coins”
print(“The bank now only has (Bank.coinsInBank) coins left”)
// Prints “The bank now only has 7900 coins left”

playerOne = nil
print(“PlayerOne has left the game”)
// Prints “PlayerOne has left the game”
print(“The bank now has (Bank.coinsInBank) coins”)
// Prints “The bank now has 10000 coins”

Deinitialization

A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how initializers are written with the init keyword. Deinitializers are only available on class types. (structure,enumeration 은 해당없음)

How Deinitialization Works

Swift automatically deallocates your instances when they are no longer needed, to free up resources. Swift handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting.

Class definitions can have at most one deinitializer per class. The deinitializer does not take any parameters and is written without parentheses:

deinit {
   // perform the deinitialization
}

Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Because an instance is not deallocated until after its deinitializer is called, a deinitializer can access all properties of the instance it is called on and can modify its behavior based on those properties (such as looking up the name of a file that needs to be closed).

Deinitializers in Action

(참고 : static function in swift https://stackoverflow.com/a/29636742 )

class Bank {
   static var coinsInBank = 10_000
   static func distribute(coins numberOfCoinsRequested: Int) -> Int {
       let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
       coinsInBank -= numberOfCoinsToVend
       return numberOfCoinsToVend
   }
   static func receive(coins: Int) {
       coinsInBank += coins
   }
}

class Player {
   var coinsInPurse: Int
   init(coins: Int) {
       coinsInPurse = Bank.distribute(coins: coins)
   }
   func win(coins: Int) {
       coinsInPurse += Bank.distribute(coins: coins)
   }
   deinit {
       Bank.receive(coins: coinsInPurse)
   }
}

var playerOne: Player? = Player(coins: 100)
print(“A new player has joined the game with (playerOne!.coinsInPurse) coins”)
// Prints “A new player has joined the game with 100 coins”
print(“There are now (Bank.coinsInBank) coins left in the bank”)
// Prints “There are now 9900 coins left in the bank”

playerOne!.win(coins: 2_000)
print(“PlayerOne won 2000 coins & now has (playerOne!.coinsInPurse) coins”)
// Prints “PlayerOne won 2000 coins & now has 2100 coins”
print(“The bank now only has (Bank.coinsInBank) coins left”)
// Prints “The bank now only has 7900 coins left”

playerOne = nil
print(“PlayerOne has left the game”)
// Prints “PlayerOne has left the game”
print(“The bank now has (Bank.coinsInBank) coins”)
// Prints “The bank now has 10000 coins”

class initailaizer를 이해하는데 좋은 예시 (swift docs 에서 가져온 내용)

original source https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID203

Designated and Convenience Initializers in Action

The following example shows designated initializers, convenience initializers, and automatic initializer inheritance in action. This example defines a hierarchy of three classes called Food, RecipeIngredient, and ShoppingListItem, and demonstrates how their initializers interact.

The base class in the hierarchy is called Food, which is a simple class to encapsulate the name of a foodstuff. The Food class introduces a single String property called name and provides two initializers for creating Food instances:

class Food {
   var name: String
   init(name: String) {
       self.name = name
   }
   convenience init() {
       self.init(name: “[Unnamed]”)
   }
}

The figure below shows the initializer chain for the Food class:

image

Classes do not have a default memberwise initializer, and so the Food class provides a designated initializer that takes a single argument called name. This initializer can be used to create a new Food instance with a specific name:

let namedMeat = Food(name: “Bacon”)
// namedMeat’s name is “Bacon”

The init(name: String) initializer from the Food class is provided as a designated initializer, because it ensures that all stored properties of a new Food instance are fully initialized. The Food class does not have a superclass, and so the init(name: String) initializer does not need to call super.init() to complete its initialization.

The Food class also provides a convenience initializer, init(), with no arguments. The init() initializer provides a default placeholder name for a new food by delegating across to the Food class’s init(name: String) with a name value of [Unnamed]:

let mysteryMeat = Food()
// mysteryMeat’s name is “[Unnamed]”

The second class in the hierarchy is a subclass of Food called RecipeIngredient. The RecipeIngredient class models an ingredient in a cooking recipe. It introduces an Int property called quantity (in addition to the name property it inherits from Food) and defines two initializers for creating RecipeIngredient instances:

class RecipeIngredient: Food {
   var quantity: Int
   init(name: String, quantity: Int) {
       self.quantity = quantity
       super.init(name: name)
   }
   override convenience init(name: String) {
       self.init(name: name, quantity: 1)
   }
}

The figure below shows the initializer chain for the RecipeIngredient class:

image

The RecipeIngredient class has a single designated initializer, init(name: String, quantity: Int), which can be used to populate all of the properties of a new RecipeIngredient instance. This initializer starts by assigning the passed quantity argument to the quantity property, which is the only new property introduced by RecipeIngredient. After doing so, the initializer delegates up to the init(name: String) initializer of the Food class. This process satisfies safety check 1 from Two-Phase Initialization above.

RecipeIngredient also defines a convenience initializer, init(name: String), which is used to create a RecipeIngredient instance by name alone. This convenience initializer assumes a quantity of 1 for any RecipeIngredient instance that is created without an explicit quantity. The definition of this convenience initializer makes RecipeIngredient instances quicker and more convenient to create, and avoids code duplication when creating several single-quantity RecipeIngredient instances. This convenience initializer simply delegates across to the class’s designated initializer, passing in a quantity value of 1.

The init(name: String) convenience initializer provided by RecipeIngredient takes the same parameters as the init(name: String) designated initializer from Food. Because this convenience initializer overrides a designated initializer from its superclass, it must be marked with the override modifier (as described in Initializer Inheritance and Overriding).

Even though RecipeIngredient provides the init(name: String) initializer as a convenience initializer, RecipeIngredient has nonetheless provided an implementation of all of its superclass’s designated initializers. Therefore, RecipeIngredient automatically inherits all of its superclass’s convenience initializers too.

In this example, the superclass for RecipeIngredient is Food, which has a single convenience initializer called init(). This initializer is therefore inherited by RecipeIngredient. The inherited version of init() functions in exactly the same way as the Food version, except that it delegates to the RecipeIngredient version of init(name: String) rather than the Food version.

All three of these initializers can be used to create new RecipeIngredient instances:

let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: “Bacon”)
let sixEggs = RecipeIngredient(name: “Eggs”, quantity: 6)

The third and final class in the hierarchy is a subclass of RecipeIngredient called ShoppingListItem. The ShoppingListItem class models a recipe ingredient as it appears in a shopping list.

Every item in the shopping list starts out as “unpurchased”. To represent this fact, ShoppingListItemintroduces a Boolean property called purchased, with a default value of false. ShoppingListItem also adds a computed description property, which provides a textual description of a ShoppingListItem instance:

class ShoppingListItem: RecipeIngredient {
   var purchased = false
   var description: String {
       var output = “(quantity) x (name)”
       output += purchased ? “ ✔” : “ ✘”
       return output
   }
}

NOTE

ShoppingListItem does not define an initializer to provide an initial value for purchased, because items in a shopping list (as modeled here) always start out unpurchased.

Because it provides a default value for all of the properties it introduces and does not define any initializers itself, ShoppingListItem automatically inherits all of the designated and convenience initializers from its superclass.

The figure below shows the overall initializer chain for all three classes:

image

You can use all three of the inherited initializers to create a new ShoppingListItem instance:

var breakfastList = [
   ShoppingListItem(),
   ShoppingListItem(name: “Bacon”),
   ShoppingListItem(name: “Eggs”, quantity: 6),
]
breakfastList[0].name = “Orange juice”
breakfastList[0].purchased = true
for item in breakfastList {
   print(item.description)
}
// 1 x Orange juice ✔
// 1 x Bacon ✘
// 6 x Eggs ✘

Here, a new array called breakfastList is created from an array literal containing three new ShoppingListItem instances. The type of the array is inferred to be [ShoppingListItem]. After the array is created, the name of the ShoppingListItem at the start of the array is changed from "[Unnamed]" to "Orange juice" and it is marked as having been purchased. Printing the description of each item in the array shows that their default states have been set as expected.