KexAri KexAri - 1 month ago 7
iOS Question

What is the use of Error, throws and catch?

I'm trying to get my head around the use of errors in swift for example I have this code:

import UIKit

class ViewController: UIViewController {

enum SomeError: Error
{
case badWord
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

do {
try checkWord()
}
catch SomeError.badWord {
print("error!")
}
catch { //This is like a defualt statement
print("Something weird happened")
}

}

func checkWord() throws {
let word = "crap"
guard word != "crap" else {
throw SomeError.badWord
}
print("Continuing the function")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}


The
checkWord
function will terminate if the word is bad. However the same behaviour can be achieved with:

func checkWord() {
let word = "crap"
guard word != "crap" else {
print("error!")
return

}
print("Continuing the function")
}


So what is the use of defining the errors and going through the catch statements?

Answer

With the 2nd implementation of checkWord, the caller of checkWord has no way to know the result of the check.

The whole idea of throwing errors and then catching them is that you can cleanly define responsibility for handling errors.

For example, your checkWord function's job is to check for bad words. But it should not make any assumptions about what should be done when a bad word is found. checkWord might be called from many different places, even by different apps (if you made it available in a framework, for example). So your checkWord function should do its check and throw an error if appropriate. Let the caller of checkWord decide how best to handle the error. It might decide to show a message to the user. It might decide to simply log it and move on. The point is, checkWord shouldn't care. Let the caller decide what's best.

Comments