SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
ERROR HANDLING IN
COCOA
AGENDA
Objective-C’s NSError
Swift’s try/catch/throws
Swift’s Result<S,F> type
Exceptions & Assertions
OBJECTIVE-C ERROR
HANDLING
NSERROR IN OBJECTIVE-C
NSError *error = nil;
NSString *string = [NSString stringWithContentsOfFile:@"test.txt"
encoding:NSUTF8StringEncoding error:&error];
if (!string) {
NSLog(@"File could not be read!");
}
if (error) {
NSLog(@"%@", error.localizedDescription);
}
NSERROR IN OBJECTIVE-C
Return value is most relevant for checking
whether an operation was successful or not [1]
Methods can return errors, but still successfully
return a value
[1] Apple Error Handling Documentation
NSERROR IN OBJECTIVE-C…

…IN THE SAD REAL WORLD
NSString *string = [NSString stringWithContentsOfFile:@"test.txt"
encoding:NSUTF8StringEncoding error:nil];
SWIFT ERROR HANDLING
SWIFT ERROR HANDLING
Swift 2 uses throws instead of NSError
Objective-C methods are bridged to Swift
accordingly:
CALLING THROWING
FUNCTIONS
You need to choose one of these 3 approaches:
handle the error with a do/catch block
Use forced-try: try!
propagate the error further up the call stack by
declaring calling function as throws
DO/CATCH IN SWIFT
do {
let content = try String(contentsOfFile: “test.txt", encoding:
NSUTF8StringEncoding)
} catch let error as NSError {
print(error)
}
DECLARING ERROR TYPES
How do you know which types of errors to catch?
Header documentation!
Unfortunately throws has no type information
DECLARING ERROR TYPES
/**
- Returns: the content of the file
- Throws: `NSError` if file could not be read
*/
func readFile() throws -> String {
//...
}
DEFINING SWIFT ERROR
TYPES
enum FileReadError: ErrorType {
case InvalidFilePath
case InvalidEncoding
case IncorrectFileFormat(actualFileFormat: String)
}
THROWING SWIFT ERROR
TYPES
/**
- Returns: The content of the file
- Throws: `FileReadError.InvalidFilePath` if file could not be read;
`FileReadError.InvalidEncoding` if file encoding does not match expected encoding;
`FileReadError.IncorrectFileFormat` if file format does not match specified one
*/
func readFile(path: String) throws -> NSData {
// ...
throw FileReadError.InvalidFilePath
}
HANDLING SWIFT ERROR
TYPES
do {
try readFile("test.txt")
} catch FileReadError.InvalidFilePath {
print("Invalid filepath")
} catch FileReadError.InvalidEncoding {
print("Invalid encoding")
} catch let FileReadError.IncorrectFileFormat(actualFileFormat) {
print("Unexpected file format: (actualFileFormat)")
} catch {
print("Unhandled Error!")
}
LIMITATIONS OF SWIFT
ERROR HANDLING
Errors don’t have type information
Error handling doesn’t work for asynchronous code
let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// error handling happens in callback
}
RESULT TYPE
Result type can represent value or error depending on
result of operation. Popular Open Source
implementation: [2]
Can be used for synchronous and asynchronous code
func search(searchString: String) -> Result<Predictions, SearchError>
[2] https://github.com/antitypical/Result
CONSUMING RESULT TYPE
func handleSearchResult(result: Result<Predictions, Reason>) -> Void {
switch result {
case let .Success(predictions):
self.locations = predictions.predictions
case .Failure(_):
self.errorHandler.displayErrorMessage(
"The search returned an error, sorry!"
)
}
}
PRODUCING RESULT TYPE
func fetchAllTrips(callback: Result<[JSONTrip], Reason> -> Void) {
// in case of success
var trips: [JSONTrip] = [/*...*/]
callback(.Success(trips))
// in case of error
var reason: Reason = .NoData
callback(.Failure(reason))
}
ASSERTIONS AND
EXCEPTIONS
EXCEPTIONS
Objective-C provides exceptions, Swift does not
Objective-C exceptions should not be caught, they are
not intended for error handling [1]
Exceptions are used to crash the app to make you
aware of a programming error
[1] Apple Error Handling Documentation
ASSERTIONS
Are used to state and verify assumptions
Typically only used at debug time
Objective-C: NSAssert…
Swift: assert, assertionFailure, 

fatalError,… [3]
[3] Swift asserts the missing manual
ASSERTIONS
SUMMARY
SUMMARY
Swift 2 uses ErrorType and throws for error
handling
Swift 2 error handling has limitations (no type info,
not suitable for async code) - Result type is a
good alternative
Exceptions and assertions are used for
unrecoverable errors
ADDITIONAL RESOURCES
ADDITIONAL RESOURCES
WWDC 106: What’s new in Swift
Javi Soto: Swift Sync and Async Error
Handling
Benjamin Encz: Swift Error Handling and
Objective-C Interop in Depth

Weitere ähnliche Inhalte

Was ist angesagt?

Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwiftScott Gardner
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functionsNAVER D2
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
ActiveRecord Query Interface
ActiveRecord Query InterfaceActiveRecord Query Interface
ActiveRecord Query Interfacemrsellars
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
Reactive programming with RxSwift
Reactive programming with RxSwiftReactive programming with RxSwift
Reactive programming with RxSwiftScott Gardner
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftColin Eberhardt
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJSMattia Occhiuto
 
systems programming lab programs in c
systems programming lab programs in csystems programming lab programs in c
systems programming lab programs in cMeghna Roy
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectRoy Derks
 
Linking the prospective and retrospective provenance of scripts
Linking the prospective and retrospective provenance of scriptsLinking the prospective and retrospective provenance of scripts
Linking the prospective and retrospective provenance of scriptsKhalid Belhajjame
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flowkang taehun
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Javascript3
Javascript3Javascript3
Javascript3mozks
 

Was ist angesagt? (20)

Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
ActiveRecord Query Interface
ActiveRecord Query InterfaceActiveRecord Query Interface
ActiveRecord Query Interface
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Reactive programming with RxSwift
Reactive programming with RxSwiftReactive programming with RxSwift
Reactive programming with RxSwift
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
systems programming lab programs in c
systems programming lab programs in csystems programming lab programs in c
systems programming lab programs in c
 
Qtp launch
Qtp launchQtp launch
Qtp launch
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript Project
 
Linking the prospective and retrospective provenance of scripts
Linking the prospective and retrospective provenance of scriptsLinking the prospective and retrospective provenance of scripts
Linking the prospective and retrospective provenance of scripts
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
Tapp 2014 (belhajjame)
Tapp 2014 (belhajjame)Tapp 2014 (belhajjame)
Tapp 2014 (belhajjame)
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Javascript3
Javascript3Javascript3
Javascript3
 

Andere mochten auch

Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOSMake School
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewMake School
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C InteropMake School
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project InfrastructureMake School
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOSMake School
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOSMake School
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOSMake School
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOSMake School
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOSMake School
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application ArchitectureMake School
 
Core Data presentation
Core Data presentationCore Data presentation
Core Data presentationjoaopmaia
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout OverviewMake School
 

Andere mochten auch (20)

Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection View
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOS
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
 
Core Data presentation
Core Data presentationCore Data presentation
Core Data presentation
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
 

Ähnlich wie Error Handling in Swift

Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JSArthur Puthin
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web AnalystsLukáš Čech
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureNicolas Corrarello
 
"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, Badoo"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, BadooYandex
 
Node js
Node jsNode js
Node jshazzaz
 
Secure code
Secure codeSecure code
Secure codeddeogun
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster DivingRonnBlack
 
WebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonWebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonGeert Van Pamel
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integrationPaul Ardeleanu
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 

Ähnlich wie Error Handling in Swift (20)

Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
JavaScript for Web Analysts
JavaScript for Web AnalystsJavaScript for Web Analysts
JavaScript for Web Analysts
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, Badoo"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, Badoo
 
Node js
Node jsNode js
Node js
 
Secure code
Secure codeSecure code
Secure code
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
 
Node intro
Node introNode intro
Node intro
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
WebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonWebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemon
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java script
Java scriptJava script
Java script
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 

Kürzlich hochgeladen

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Kürzlich hochgeladen (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

Error Handling in Swift

  • 1.
  • 5. NSERROR IN OBJECTIVE-C NSError *error = nil; NSString *string = [NSString stringWithContentsOfFile:@"test.txt" encoding:NSUTF8StringEncoding error:&error]; if (!string) { NSLog(@"File could not be read!"); } if (error) { NSLog(@"%@", error.localizedDescription); }
  • 6. NSERROR IN OBJECTIVE-C Return value is most relevant for checking whether an operation was successful or not [1] Methods can return errors, but still successfully return a value [1] Apple Error Handling Documentation
  • 7. NSERROR IN OBJECTIVE-C…
 …IN THE SAD REAL WORLD NSString *string = [NSString stringWithContentsOfFile:@"test.txt" encoding:NSUTF8StringEncoding error:nil];
  • 9. SWIFT ERROR HANDLING Swift 2 uses throws instead of NSError Objective-C methods are bridged to Swift accordingly:
  • 10. CALLING THROWING FUNCTIONS You need to choose one of these 3 approaches: handle the error with a do/catch block Use forced-try: try! propagate the error further up the call stack by declaring calling function as throws
  • 11. DO/CATCH IN SWIFT do { let content = try String(contentsOfFile: “test.txt", encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error) }
  • 12. DECLARING ERROR TYPES How do you know which types of errors to catch? Header documentation! Unfortunately throws has no type information
  • 13. DECLARING ERROR TYPES /** - Returns: the content of the file - Throws: `NSError` if file could not be read */ func readFile() throws -> String { //... }
  • 14. DEFINING SWIFT ERROR TYPES enum FileReadError: ErrorType { case InvalidFilePath case InvalidEncoding case IncorrectFileFormat(actualFileFormat: String) }
  • 15. THROWING SWIFT ERROR TYPES /** - Returns: The content of the file - Throws: `FileReadError.InvalidFilePath` if file could not be read; `FileReadError.InvalidEncoding` if file encoding does not match expected encoding; `FileReadError.IncorrectFileFormat` if file format does not match specified one */ func readFile(path: String) throws -> NSData { // ... throw FileReadError.InvalidFilePath }
  • 16. HANDLING SWIFT ERROR TYPES do { try readFile("test.txt") } catch FileReadError.InvalidFilePath { print("Invalid filepath") } catch FileReadError.InvalidEncoding { print("Invalid encoding") } catch let FileReadError.IncorrectFileFormat(actualFileFormat) { print("Unexpected file format: (actualFileFormat)") } catch { print("Unhandled Error!") }
  • 17. LIMITATIONS OF SWIFT ERROR HANDLING Errors don’t have type information Error handling doesn’t work for asynchronous code let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!) let session = NSURLSession.sharedSession() session.dataTaskWithRequest(request) { (data, response, error) -> Void in // error handling happens in callback }
  • 18. RESULT TYPE Result type can represent value or error depending on result of operation. Popular Open Source implementation: [2] Can be used for synchronous and asynchronous code func search(searchString: String) -> Result<Predictions, SearchError> [2] https://github.com/antitypical/Result
  • 19. CONSUMING RESULT TYPE func handleSearchResult(result: Result<Predictions, Reason>) -> Void { switch result { case let .Success(predictions): self.locations = predictions.predictions case .Failure(_): self.errorHandler.displayErrorMessage( "The search returned an error, sorry!" ) } }
  • 20. PRODUCING RESULT TYPE func fetchAllTrips(callback: Result<[JSONTrip], Reason> -> Void) { // in case of success var trips: [JSONTrip] = [/*...*/] callback(.Success(trips)) // in case of error var reason: Reason = .NoData callback(.Failure(reason)) }
  • 22. EXCEPTIONS Objective-C provides exceptions, Swift does not Objective-C exceptions should not be caught, they are not intended for error handling [1] Exceptions are used to crash the app to make you aware of a programming error [1] Apple Error Handling Documentation
  • 23. ASSERTIONS Are used to state and verify assumptions Typically only used at debug time Objective-C: NSAssert… Swift: assert, assertionFailure, 
 fatalError,… [3] [3] Swift asserts the missing manual
  • 26. SUMMARY Swift 2 uses ErrorType and throws for error handling Swift 2 error handling has limitations (no type info, not suitable for async code) - Result type is a good alternative Exceptions and assertions are used for unrecoverable errors
  • 28. ADDITIONAL RESOURCES WWDC 106: What’s new in Swift Javi Soto: Swift Sync and Async Error Handling Benjamin Encz: Swift Error Handling and Objective-C Interop in Depth