C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
AppendSpecial: This is a worthless method, but it throws some example exceptions. Please note its use of the "throws" keyword.
Guard: A guard is an if-statement that must exit the current block (as with throw) if the specified condition is not true.
Do, try, catch: These keywords wrap a func call that may throw an exception (one decorated with "throws").
Result: AppendSpecial() is called but it throws a PartTooShort error. We catch this and display a special message.
Swift program that uses try, throw, catch
// Some special error types.
enum ErrorSpecial: Error {
case PartTooShort
case PartTooLong
}
func appendSpecial(value: String, part: String) throws -> String {
// Throw an exception unless "part" is an appropriate length.
guard part.characters.count > 0 else {
throw ErrorSpecial.PartTooShort
}
guard part.characters.count < 10 else {
throw ErrorSpecial.PartTooLong
}
// Append.
return value + part
}
do {
// Try to call our method.
try appendSpecial(value: "cat", part: "")
} catch ErrorSpecial.PartTooShort {
// The method had a disaster.
print("Part was too short!")
}
Output
Part was too short!
Here: The divideBy method throws errors when its argument is 0. We call divideBy twice.
First: We use "try!" to convert the error to an optional, and then get the inner value. The program prints "2."
Second: We use optional binding, in an "if let" statement, with the divideBy func. We evaluate the optional as part of the "if let."
Swift program that converts errors to optionals
enum DivErrors : Error {
case Invalid
}
func divideBy(value: Int) throws -> Int {
// Throw an error if argument is equal to 0.
guard value != 0 else {
throw DivErrors.Invalid
}
return 20 / value
}
// Convert error to optional.
// ... Then get value from optional.
let result = try! divideBy(value: 10)
print(result) // Prints 2.
// Convert error to optional.
if let result2 = try? divideBy(value: 0) {
print(result2) // Not reached.
}
Output
2