ios - What is the use of Error, throws and catch? -
i'm trying head around use of errors in swift example have code:
import uikit class viewcontroller: uiviewcontroller { enum someerror: error { case badword } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. { try checkword() } catch someerror.badword { print("error!") } catch { //this defualt statement print("something weird happened") } } func checkword() throws { let word = "crap" guard word != "crap" else { throw someerror.badword } print("continuing function") } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } }
the checkword
function terminate if word bad. same behaviour can achieved with:
func checkword() { let word = "crap" guard word != "crap" else { print("error!") return } print("continuing function") }
so use of defining errors , going through catch statements?
with 2nd implementation of checkword
, caller of checkword
has no way know result of check.
the whole idea of throwing errors , catching them can cleanly define responsibility handling errors.
for example, checkword
function's job check bad words. should not make assumptions should done when bad word found. checkword
might called many different places, different apps (if made available in framework, example). checkword
function should check , throw error if appropriate. let caller of checkword
decide how best handle error. might decide show message user. might decide log , move on. point is, checkword
shouldn't care. let caller decide what's best.
Comments
Post a Comment