一个老外的博客:
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