Search Your Question

Difference between normal function and function ending throw

Function ending with throw can throw error but normal function can not throw error it can just return value.


Lets take example :

1. Custom error enum

enum ErrorsToThrow: Error {
    case fileNotFound
    case fileNotReadable
    case fileSizeIsTooHigh
}

2. Make function which can throw error

func readFiles(path:Stringthrows  ->String {
        if path == "" {
            throw ErrorsToThrow.fileNotFound
        }
        return "Data from file"

    }

3. Calling readFiles function
   do {
            let dataFromString = tryreadFiles(path: "")
            print(dataFromString)
        } catch ErrorsToThrow.fileNotFound {
            print("error generated1")
        } catch ErrorsToThrow.fileNotReadable {
            print("error generated2")
        } catch ErrorsToThrow.fileSizeIsTooHigh {
            print("error generated3")
        } catch {
                print("error")
        }

Now, let's analysis.

1. If in #2, function is not ending with throws can not throw error. But our function can throw error.
2. In #3, we have used try?, so if readFiles function return nil instead of throwing error. So in our case print(dataFromString) statement executed and it will nil means printing nil.

3. If try! is written and if function throw error, then fatal error will be occured and program will be crashed as we ensure that error will not occur by putting ! .
4. So if we want to execute catch statement then we have to use only try . try always used with do-catch.
5. try? and try! does not need do-catch block.

No comments:

Post a Comment

Thanks