Error Handling in Swift 2.0.
Error handling is the process of responding to error conditions in your program. Swift provides class that support for throwing, catching, propagating, and manipulating recoverable errors at runtime.
In Swift 2.0, if you want to throw an error, the object thrown must conform to the ErrorType protocol. As you may have expected, NSError conforms to this protocol. Enumerations are used for classifying errors.
In Swift 2.0, if you want to throw an error, the object thrown must conform to the ErrorType protocol. As you may have expected, NSError conforms to this protocol. Enumerations are used for classifying errors.
Simple Error Handling Try-Catch :
do{
let encrypted = try myfunctionCalling()
print(encrypted)
}catch { print("Something went wrong!")
}
let encrypted = try myfunctionCalling()
print(encrypted)
}catch { print("Something went wrong!")
}
ErrorType Protocol : Define the ErrorType Protocol as below.
enum AwfulError : ErrorType {
case Bad
case Worse
case Terrible
}
case Bad
case Worse
case Terrible
}
throws Error : Now make one function with throws keyword, This function have one or more throw errors.
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()
}
// 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()
}
Function call by do-try-catch :
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!
}
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!
}
Thanks
Error Handling in Swift 2.0.
Reviewed by KIRIT MODI
on
00:18:00
Rating:
No comments: