Farlanki

swift 2.0的异常处理

字数统计: 116阅读时长: 1 min
2015/10/18 Share

可以用enum类型建立自定义的错误类型:

1
2
3
4
enum MyError: ErrorType {  
case NotExist
case StartWithWrongLetter
}

定义抛出异常的函数:

1
2
3
4
5
func handleString(String : String) throws -> String
{
//code
throw MyError.NotExist
}

捕捉异常

1
2
3
4
do{
try // function that throws
}
catch MyError.NotExist {print("not exist")}

try?

1
var myString = try? handleString(oldString)

与以下等价

1
2
3
4
do{
var myString = try handleString(oldString)
}
catch{myString = nil}

try!可以不处理异常,一旦出现异常便是运行时错误

1
var myString = try! handleString(oldString)
CATALOG