TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf