Swift Error Handling: try, catch

Use the try and catch keywords to handle exceptions. Throw with a custom Error.
Try, catch. A file may not exist. A division may not be possible. A program in Swift cannot execute without possible errors. With try and catch, we handle these problems.
In a do-block, we call methods that may crash with the "try" keyword. An optional catch block is reached when an error does occur. Nothing happens if no error is raised.
Primary example. This program introduces many concepts and syntax forms. It first specifies an ErrorSpecial enum, which is an Error. All exceptions must derive from Error.

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!
Convert errors, optionals. An error can be converted to an optional. We use the "try?" or "try!" keywords when calling the exception-throwing method.Optional

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
File handling. Another common cause of exceptions (or the need to use them) is file handling. For example, the NSString contentsOfFile call may throw exceptions.File: try NSString
In exception handling, we use an alternative control flow. This is powerful. But it introduces complexity and keywords. It is an established way to improve program quality.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to