Learn swift--error handling against Java (error handling)

Source: Internet
Author: User
Tags try catch

Brief introduction

In the case of exception handling, Java is similar to Swift, either throwing an exception or handling the exception itself, but the syntax is somewhat different.

    • Throwing exceptions Java and Swift are all using the throws keyword, java behind the parentheses, in front of the curly braces, and swift in front of the return value arrows.
    • Handle Exceptions yourself Java uses the try catch structure, and Swift uses the Do-catch structure, which can also match multiple catch blocks.

The catch block in Java is either a system-provided or a custom exception class, the custom exception class must inherit the exception class, and Swift's catch block is each value of an enum, which requires the enum to implement the ErrorType protocol. Of course, it can be other types, but you have to implement the ErrorType protocol, which is the most enumerated.
Similarly, if a catch does not match, an external scope is required to handle it.

Represents and throws an error

In Swift, the error is represented by a value of the type that conforms to the ErrorType protocol. This null protocol indicates that the type can be used for error handling.

The enumeration type of Swift is particularly suitable for building a set of related error states, and the associated values of the enumeration can also provide additional information about the error state. For example, you can indicate an error state that may occur when you operate a vending machine in a game:

enum VendingMachineError: ErrorType {    case InvalidSelection                    //选择无效    case//金额不足    case OutOfStock                          //缺货}

Throwing an error can let you indicate that an unexpected situation has occurred, causing the normal execution process to fail to execute. Throws an error using the throws keyword. For example, the following code throws an error indicating that the vending machine also requires 5 coins:

throw5)
Handling Errors

As mentioned earlier, there are two ways to handle errors, throw them, and handle them yourself.

    • Throw an error with the throwing function
func canThrowErrors() throws -> Stringfunc cannotThrowErrors() -> String

Look at an example.

let favoriteSnacks = [    "Alice""Chips",    "Bob""Licorice",    "Eve""Pretzels"String, vendingMachine: VendingMachine) throws {    let"Candy Bar"    try vendingMachine.vend(itemNamed: snackName)}
    • Handling Errors with Do-catch statements
do {    try expression    catch1 {    catch2where condition {    statements}

Look at an example.

varVendingmachine = Vendingmachine () vendingmachine.coinsdeposited =8 Do{TryBuyfavoritesnack ("Alice",Vendingmachine: Vendingmachine)}Catchvendingmachineerror.invalidselection {Print("Invalid Selection.")}CatchVendingmachineerror.outofstock {Print("Out of Stock.")}CatchVendingmachineerror.insufficientfunds ( Letcoinsneeded) {Print("insufficient funds. Please insert an additional \ (coinsneeded) coins. ")}
Converting an error to an optional value

You can use try? To handle an error by converting an error to an optional value. If an error is thrown when evaluating the try expression, then the value of the expression is nil. For example, the following code has the same values as X and y:

func someThrowingFunction() throws -> Int {    ...try? someThrowingFunction()let y: Int?do {    try someThrowingFunction()} catch {    y = nil}

Look at an example.

funcData? {    ifletdata = try? fetchDataFromDisk() { return data }    ifletdata = try? fetchDataFromServer() { return data }    return nil}
Disable Error delivery

Sometimes you know that a throwing function actually does not throw an error at run time, in which case you can write try! in front of the expression to disable error delivery, which wraps the call in a run-time assertion that the assertion does not throw an error. If you actually throw an error, you will get a run-time error.

For example, the following code uses the LoadImage (_:) function, which loads a picture resource from a given path and throws an error if the picture cannot be loaded. In this case, because the picture is bound to the application, the runtime does not throw an error, so it is appropriate to disable error delivery:

lettry! loadImage("./Resources/John Appleseed.jpg")
Specify cleanup operations

You can use the defer statement to execute a series of statements when you are about to leave the current code block. This statement allows you to perform some necessary cleanup work, regardless of the way you leave the current block of code, whether it is due to throwing an error, or because of a statement such as return or break. For example, you can use the defer statement to ensure that the file descriptor is closed and that the manually allocated memory is freed.

func doSomethingWithDefer(){    1    openDirectory()    2    defer{closeDirectory()}    3    openFile()    4    defer{closeFile()}    // 做其他杂七杂八事情...}

For example, Dosomethingwithdefer () to invoke two methods to complete this action, after each method call is completed there is a defer keyword contains the code, the code will not be executed immediately, but is pressed into a stack, until the method runs to the end of the time, Pop it out of the stack. Execute these methods at once.

Learn swift--error handling against Java (error handling)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.