Exploring error handling

Things don't always go as you would expect, so you need to keep that in mind as you write apps. You need to think of ways that your app might fail, and what to do if it does.

Let's say you have an app that needs to access a web page. However, if the server where that web page is located is down, it is up to you to write the code to handle the error—for example, trying an alternative web server or informing the user that the server is down.

First, you need an object that conforms to Swift's Error protocol:

  1. Type in the following code into your playground:
// Error handling
// Create an enum that adopts the error protocol
enum WebpageError: Error {
case success
// associate server response value of type Int with failure
case failure(Int)
}

The code you entered declares an enumeration, WebpageError, that has adopted the Error protocol. It has two values, success, and failure(Int). You can associate Int with the failure value, which will be used to store the server response code.

  1. Type in the following code after the WebpageError declaration:
// getWebpage will throw an error if the site is down
func getWebpage(uRL: String, siteUp: Bool) throws -> String {
if siteUp == false {
throw WebpageError.failure(404)
}
return "Success"
}

This function, getWebpage(url:siteUp:), takes two parameters:

  • uRL contains a String representing a URL, such as http://www.apple.com.
  • siteUp is a Bool that is used to check whether a website is online. It is set to true if the website is online and false if the website is not.

If siteUp is true, getWebpage returns "Success". If siteUp is false, the program will throw an error with the server response code.

  1. Type in the following code after the function declaration and run it:
let webpageURL = "http://www.apple.com"
let websiteUp = true

try getWebpage(uRL: webpageURL, siteUp: websiteUp)

Since websiteUp is true, "success" will appear in the Results area.

  1. Change the value of websiteUp to false and run it. Your program crashes and the error is displayed in the Debug area. Of course, it is always better if you can handle errors without making your program crash. One way to do this is by using do-catch.
  1. Modify your code as shown and run it:
do {
let status = try getWebpage(uRL: webpageURL, siteUp: websiteUp)
print(status)
} catch {
print(error)
}

The do block tries to execute the getWebpage(url:siteUp:) function and prints the status if successful. If there is an error, instead of crashing, the statements in the catch block are executed, and the error appears in the Debug area.

For more information on error handling, visit https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.193.158