Swift Learning note 9--error control

Source: Internet
Author: User

There are 4 ways to handle errors in 1.Swift. You can pass the error that the function throws to the code that called the function, handle the error with the do-catch statement, treat the error as an optional type, or assert that the error does not occur at all.

Error handling in 2.wift does not involve lifting the call stack, which is a computationally expensive process. For this, the throw performance characteristics of a statement can be return comparable to a statement.

3. A function marked with a throws keyword is called the throwing function . If the function indicates a return value type, the throws keyword needs to be written in -> front of the arrow (). Only the throwing function can pass an error. Any error that is thrown inside a non-throwing function can only be handled inside the function.

4. You can use to try? handle errors by converting an error to an optional value. If try? an error is thrown when evaluating an expression, the value of the expression is nil .

try? somethrowingfunction ()//equivalent to let Y:int?  Do {    trycatch  {    = Nil}

5. You can disable error delivery by writing in front of the expression try! , which wraps the call in a run-time assertion where an assertion does not throw an error. If you actually throw an error, you will get a run-time error.

6. You can use defer a 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 .

if exists (filename) {        = open (filename)        defer {            close (file)        }               //  The close (file) is called here, at the end of the scope.     }

Swift Learning note 9--error control

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.