Created
May 20, 2018 14:47
-
-
Save mediter/833afa99ffab78d440c719173a230676 to your computer and use it in GitHub Desktop.
[Error Handling] #swift #error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
do { | |
//要做一些操作 | |
let str = try NSString(contentsOfFile: filePath,encoding: NSUTF8StringEncoding)//要尝试做的事情 | |
} catch let err as NSError {//如果失败则进入catch代码块 | |
err.description | |
} | |
二,错误类型 | |
在Swift中错误类型必须遵从ErrorType 协议,其次考虑到错误类型的匹配,它应该被设计成为枚举类型,枚举类型非常适合将一组相关值关联起来。 | |
如果我们编写访问数据库表程序,实现对表数据插入、删除、修改和查询等操作,我们会需要类似如下代码的错误类型: | |
enum DAOError: ErrorType { | |
case NoData | |
case PrimaryKeyNull | |
} | |
NoData表示没有数据情况,PrimaryKeyNull表示表的主键(Primary Key)为空情况。 | |
那么我们就可以通过如下代码捕获错误。 | |
do { | |
//try 访问数据表函数或方法 | |
} catch DAOError.NoData { | |
print("没有数据。") | |
} catch DAOError.PrimaryKeyNull { | |
print("主键为空。") | |
} | |
作者:星空梦想 | |
链接:https://www.jianshu.com/p/7b6d21014a31 | |
來源:简书 | |
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment