SlideShare a Scribd company logo
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

More Related Content

What's hot

Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
Scott Gardner
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
[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
NAVER D2
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
Fabio Biondi
 
ActiveRecord Query Interface
ActiveRecord Query InterfaceActiveRecord Query Interface
ActiveRecord Query Interfacemrsellars
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
Reactive programming with RxSwift
Reactive programming with RxSwiftReactive programming with RxSwift
Reactive programming with RxSwift
Scott Gardner
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
Colin Eberhardt
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
Mattia 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
 
Qtp launch
Qtp launchQtp 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
Roy 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 scripts
Khalid Belhajjame
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
kang 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 RAMALINGAM
SaraswathiRamalingam
 
Tapp 2014 (belhajjame)
Tapp 2014 (belhajjame)Tapp 2014 (belhajjame)
Tapp 2014 (belhajjame)
Khalid Belhajjame
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
Javascript3
Javascript3Javascript3
Javascript3mozks
 

What's hot (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
 

Viewers also liked

Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
Make 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 View
Make School
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
Make School
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
Make School
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
Make School
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
Make School
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
Make School
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
Make School
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
Make 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 iOS
Make School
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
Make School
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
Make School
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
Make School
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
Make School
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
Make School
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
Make School
 
Core Data presentation
Core Data presentationCore Data presentation
Core Data presentation
joaopmaia
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
Make School
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
Make School
 

Viewers also liked (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
 

Similar to Error Handling in Swift

Clean & Typechecked JS
Clean & Typechecked JSClean & Typechecked JS
Clean & Typechecked JS
Arthur Puthin
 
"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
Lukáš Č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 Trees
Jamund Ferguson
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
Nicolas Corrarello
 
"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, Badoo"Writing Maintainable JavaScript". Jon Bretman, Badoo
"Writing Maintainable JavaScript". Jon Bretman, Badoo
Yandex
 
Node js
Node jsNode js
Node jshazzaz
 
Secure code
Secure codeSecure code
Secure code
ddeogun
 
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
Daniel Fisher
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
RonnBlack
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
Ted Husted
 
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
Geert Van Pamel
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
Paul 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 js
Francois Zaninotto
 

Similar to 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
 

Recently uploaded

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 

Recently uploaded (20)

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 

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