Error handling in swift

Error handling is the process of responding to and recovering from error conditions in your program. In many situations we may have to deal with errors. Sometimes we also have to let the co-workers know that the program throws error. I will try to explain every aspects of error handling here in this article.

func readFiles(path:String) ->String {if fileNotFound {print(“fileNotFound”)} else if fileNotReadable {print(“fileNotReadable”)} else if fileSizeIsTooHigh {print(“fileSizeIsTooHigh”)}return “Data from file”}
enum ErrorsToThrow: Error {case fileNotFoundcase fileNotReadablecase fileSizeIsTooHigh}

Design Throwable Function

func canThrowErrors() throws -> Stringfunc cannotThrowErrors() -> String
func readFiles(path:String) throws ->String {if fileNotFound {throw ErrorsToThrow.fileNotFound} else if fileNotReadable {throw ErrorsToThrow.fileNotReadable} else if fileSizeIsTooHigh {throw ErrorsToThrow.fileSizeIsTooHigh}return “Data from file”}
do {let dataFromString = try? readFiles(path: “path for file”)} catch ErrorsToThrow.fileNotFound {print(“fileNotFound”)} catch ErrorsToThrow.fileNotReadable {print(“fileNotReadable”)} catch ErrorsToThrow.fileSizeIsTooHigh {print(“fileSizeIsTooHigh”)}

Initializers that throws :

enum ErrorsToThrow: Error {case nameIsEmpty}
class Human {var name:String?init(name:String?) throws {guard let name = name else {throw ErrorsToThrow.nameIsEmpty} = name}}
do {let humanObj = try Human(name: nil)} catch ErrorsToThrow.nameIsEmpty {print(“The name is empty.Cannot initialize human”)}// prints The name is empty.Cannot initialize human

try vs try! vs try?

let humanObj1 = try? Human(name: “He-man”) // returns Human?let humanObj2 = try? Human(name: nil) // nil (humanObj2 is an optional which can handle nil)
let humanObj1 = try! Human(name: “He-man”) // returns Humanlet humanObj2 = try! Human(name: nil) // nil and the app will crash

Recommended articles for you:

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

iOS and tvOS developer, dreamer, photographer 🤨