Not "real language"? Details about error handling in Swift 2.0

Source: Internet
Author: User

At this year's Global Developers Conference (Worldwide Developers Conference, WWDC), Apple announced the launch of Swift2.0, the language's chief architect, Chris Lattner, said that Swift 2.0 is mainly in the basic language grammar, Security and format aesthetics are improved in three ways. In addition to these new features, there is also the optimization, modification and beautification of the grammar, and finally the most influential error handling mechanism in Swift 1.x.

This is because you can't avoid it at all. If you intend to use Swift 2.0, you must accept the mechanism of error handling, and the error handling mechanism will change the way cocoa and cocoa touch frameworks use Nserror to interact with methods.

a moment in history: a humble beginning

As we all know, the swift language has been introduced as Objective-c's current alternative language and is the "lingua-language" for OS X and iOS application development. In the original version, Objective-c did not have a native exception handling mechanism. Later by adding the NSException class, there are ns_during, Ns_handler and Ns_endhandler macros that have exception handling. This scheme is now called "Classic exception Handling", and these macros are based on the two C-language functions of setjmp () and longjmp ().

Exception trapping (exception-catching) looks as follows, and any exceptions thrown between ns_during and Ns_handler macros will cause code to be executed between the Ns_handler and Ns_endhandler macros.

[CPP]View Plaincopy
    1. Ns_during
    2. //Call a Dangerous method or function This raises an exception:
    3. [obj Someriskymethod];
    4. Ns_handler
    5. NSLog (@"Oh no!");
    6. [Anotherobj Makeitright];
    7. Ns_endhandler

Here's how to trigger an exception immediately (still available now):

[CPP]View Plaincopy
    1. -(void) Someriskymethod
    2. {
    3. [NSException raise:@"KaBlam"
    4. format:@"This method was not implemented yet. Do not call! "];
    5. }

As you can imagine, this kind of manual handling of anomalies is teasing the early Cocoa Framework program developers. But these programmers are not up to this, because they seldom use this way. Exceptions are often categorized as catastrophic, unrecoverable errors, such as errors by programmers, in the cocoa or cocoa touch framework. The above-someriskymethod is a good example of an exception that is thrown because the implementation part is not ready. In the cocoa and cocoa touch frameworks, recoverable errors are handled by the Nserror class that is discussed later.

Native exception Handling

I think because of the objective-c of the classic exception handling mechanism of the corresponding manual processing way to feel upset, so Apple in Mac OS X 10.3 (October 2003) released the native exception handling mechanism, there is no iOS system. This essentially grafted C + + exception handling to the OBJECTIVE-C. The structure of exception handling now looks like this:

[CPP]View Plaincopy
  1. @try {
  2. [obj Someriskymethod];
  3. }
  4. @catch (SomeClass *exception) {
  5. //Handle the error.
  6. //Can Use the exception object to gather information.
  7. }
  8. @catch (SomeOtherClass *exception) {
  9. // ...  
  10. }
  11. @catch (id alltherest) {
  12. // ...  
  13. }
  14. @finally {
  15. //Code that's executed whether an exception are thrown or not.
  16. //use for cleanup.
  17. }

Native exception handling gives you the opportunity to specify different @catch parts for each exception type. Regardless of the @try result, the @finally executes its corresponding code.

Although native exception handling throws a NSException exception as expected, the most definitive approach is "@throw <expression>;" Statement. Usually you throw a nsexception instance, but maybe something will be thrown.

Nserror

Although Objective-c native and classic exception handling has many advantages, cocoa and cocoa touch framework application developers still rarely use exceptions, but instead restrict the program from the unrecoverable errors that programmers cause. Use the Nserror class to handle recoverable errors, which are earlier than using exception handling. The Swift 1.x also inherits the Nserror style.

In Swift 1.x, the methods and functions of cocoa and cocoa touch may not return a Boolean type of false or nil to represent a failed (failure) object. In addition, the Nserrorpointer object is treated as a parameter to return specific failure information. The following is a typical example:

[CPP]View Plaincopy
  1. A local variable to store an Error object if one comes back:
  2. var error:nserror?
  3. Success is a Bool:
  4. Let success = Somestring.writetourl (Someurl,
  5. atomically: True,
  6. Encoding:nsutf8stringencoding,
  7. Error: &error)
  8. If!success {
  9. //Log information about the error:
  10. println ("Error writing to URL: \ (error!)")
  11. }

Errors caused by programmers can be marked with the SWIFT Standard library function fatalerror ("error message"), which is logged as an error message on the console and aborts execution unconditionally. You can also use ASSERT (), assertionfailure (), precondition (), and preconditionfailure () functions.

When Swift was first released, some non-Apple platform developers were ready with torches and pitchfork. They claim that Swift cannot be considered a "real language" because it lacks exception handling. But the cocoa and cocoa touch community ignored it, and we knew Nserror and NSException were there. Personally, I believe Apple is still thinking about the right way to implement error and exception handling. I also think that until the problem is solved, Apple will open the swift source. All of this was cleared up in Swift 2.0.

Error Handling in Swift 2.0

In Swift 2.0, if you want to throw an error, the object thrown must conform to the ErrorType protocol. Perhaps as you wish, Nserror is in compliance with the agreement. Enumerations are used here to classify errors.

[CPP]View Plaincopy
    1. Enum Awfulerror:errortype {
    2. Case Bad
    3. Case Worse
    4. Case Terrible
    5. }

Then, if a function or method that can throw one or more errors is flagged by the throws keyword:

[CPP]View Plaincopy
  1. Func Dodangerousstuff () throws-someobject {
  2. //If Something bad happens throw the error:
  3. Throw Awfulerror.bad
  4. //If Something worse happens, throw another error:
  5. Throw Awfulerror.worse
  6. //If Something terrible happens, you know and do:
  7. Throw awfulerror.terrible
  8. //If you made it here and you can return:
  9. return Someobject ()
  10. }

In order to catch the error, the new Do-catch statement appears:

[CPP]View Plaincopy
  1. do {
  2. Let Theresult = try Obj.dodangerousstuff ()
  3. }
  4. Catch Awfulerror.bad {
  5. //Deal with badness.
  6. }
  7. Catch Awfulerror.worse {
  8. //Deal with worseness.
  9. }
  10. Catch Awfulerror.terrible {
  11. //Deal with terribleness.
  12. }
  13. Catch ErrorType {
  14. //Unexpected error!
  15. }

There are some similarities between this do-catch statement and the switch statement, and the errors captured are exhaustive, so you can use this style to catch thrown errors. Also pay attention to the use of the keyword try. It is intended to explicitly indicate the line of code thrown, so you can immediately find out where the error is when reading the code.

The variant of the keyword try is "try!". This keyword probably also applies to errors that are caused by programmers. If you use "try!" Tag a method in a called thrown object, you tell the compiler that this error never occurs, and you do not need to capture it. If the statement itself produces errors (error) and the application stops executing, then you start debugging.

[CPP]View Plaincopy
    1. Let Theresult = try! obj.dodangerousstuff ()

Interaction with the cocoa and cocoa touch frames

Now the question is, how do you deal with Grandpa's Nserror API in Swift 2.0? Apple has done a lot of work on unified Code behavior in Swift 2.0, and has prepared the way for a future write to Swift's framework. Methods and functions that can generate nserror instances in cocoa and cocoa touch have Apple's signature (signature), which can be automatically converted to Swift's new error handling.

For example, this nsstring constructor (initializer) has the following signature in Swift 1.x:

[CPP]View Plaincopy
    1. Convenience init? (Contentsoffile path:string,
    2. Encoding Enc:uint,
    3. Error Error:nserrorpointer)

In Swift 2.0, the signature is converted to:

[JS]View Plaincopy
    1. Convenience init (Contentsoffile path:string,
    2. Encoding Enc:uint) throws

Note: In Swift 2.0, the constructor is no longer marked as failable, it does not require nserrorpointer to do the arguments, but instead explicitly indicates a potential failure by throwing an exception.

The following example uses this new signature:

[CPP]View Plaincopy
    1. do {
    2. Let str = try NSString (contentsoffile: "Foo.bar",
    3. encoding:nsutf8stringencoding)
    4. }
    5. Catch let error as nserror {
    6. Print (error.localizeddescription)
    7. }

Notice how the error is captured and how it is converted into an Nserror instance so that you can get information about its similar API. In fact, any instance of the ErrorType type can be converted to the Nserror type.

Finally, say @finally.

The attentive reader may have noticed that Swift 2.0 introduced a new Do-catch statement, rather than a do-catch-finally. How do you specify the code that must be run, regardless of whether the error is caught or not? To do this, you can now use the defer statement to defer execution of the code block until the current scope ends.

[CPP]View Plaincopy
  1. Some Scope:
  2. {
  3. //Get some resource.
  4. Defer {
  5. //Release resource.
  6. }
  7. //Do things with the resource.
  8. //Possibly return early if an error occurs.
  9. } //Deferred code is executed at the end of the scope.

Swift 2.0 condenses the error-handling mechanism of cocoa and cocoa touch into a modern-style usage, which is a great job and will make many programmers feel more cordial. Uniform behavior is a good location, and the swift language and its inherited framework evolve.

(Translation/Baiyunpeng Friendship Review/Wang Yang)

Article Source: Big Nerd Ranch

Author Profile: Juan Pablo Claude, from Santiago, the capital of Chile, graduated from the University of North Carolina at Chapel Hill (University of Nord Carolina at Chapel Hill) and received a PhD in chemistry, After entering the University of Alabama at Birmingham (University of Alabama at Birmingham) teaches. At the end of 2005, Cocoa and Django Framework program developers joined the big Nerd Ranch. Prior to that, there was a DOS environment under C Programming, in Windows environment using C + + to write data analysis application experience.

Translator Profile: Baiyunpeng, mobile app developer, personal blog: http://baiyunpeng.com.

Not "real language"? Details about error handling in Swift 2.0

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.