10 -- 关于NSError

一个老外的博客:
https://www.bignerdranch.com/blog/error-handling-in-swift-2/
摘要:
A

 NS_DURING
*// Call a dangerous method or function that raises an           exception:*
 [obj **someRiskyMethod**];
NS_HANDLER
NSLog(@"Oh no!");
[anotherObj **makeItRight**];
NS_ENDHANDLER

B

**-** (**void**)someRiskyMethod
{
[NSException **raise**:@"Kablam"
            **format**:@"This method is not implemented yet. Do     not call!"];
}

C

**@try** {
[obj **someRiskyMethod**];
}
**@catch** (SomeClass *****exception) {
*// Handle the error.*
*// Can use the exception object to gather information.*
}
**@catch** (SomeOtherClass *****exception) {
*// ...*
}

D

**@catch** (id allTheRest) {
*// ...*
}
**@finally** {
*// Code that is executed whether an exception is thrown or not.*
*// Use for cleanup.*
}

E

*// A local variable to store an error object if one comes back:*
**var** error: **NSError**?
*// success is a Bool:*
**let** success **=** someString**.****writeToURL**(someURL,
                                atomically: **true**,
                                encoding: **NSUTF8StringEncoding**,
                                error: **&**error)
**if** **!**success {
*// Log information about the error:*
**println**("Error writing to URL: \(error**!**)")
}

  **enum** **AwfulError**: **ErrorType** {
  **case** **Bad**
  **case** **Worse**
  **case** **Terrible**

}

F

func  doDangerousStuff () throws ->SomeObject {
*// If something bad happens throw the error:*
throw  AwfulError Bad

*// If something worse happens, throw another error: *
throw **AwfulError****.****Worse**

*// If something terrible happens, you know what to do: *
throw **AwfulError****.****Terrible**

*// If you made it here, you can return:*
**return** **SomeObject**()
}

G

**do** {
**let** theResult **=** try obj**.****doDangerousStuff**()
}
catch **AwfulError****.****Bad** {
*// Deal with badness.*
}
catch **AwfulError****.****Worse** {
*// Deal with worseness.*
}
catch **AwfulError****.****Terrible** {
*// Deal with terribleness.*
}
catch **ErrorType** {
*// Unexpected error!*
}

H

let** theResult **=** try**!** obj**.****doDangerousStuff**()`

convenience **init**(contentsOfFile path: **String**,
             encoding enc: **UInt**) throws
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,819评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,180评论 4 61
  • 看到这里,我相信你已经知道了作用域的概念了,以及根据声明的位置和方式将变量分配给作用域的相关原理了。函数作用域和块...
    我就是z阅读 442评论 1 2
  • 前几天,司法部发布了"2016年国家司法考试公告",确定9月24日、25日为今年国家司法考试时间。 看到这一消息,...
    子诺不离阅读 4,830评论 8 57
  • 名日精进【打卡第210天】: 姓名:余成杰 公司:贞观电器 盛和塾《六项精进》224期学员 【知-学习】 《六项精...
    余成杰阅读 233评论 0 0