Catch any mistake, specially unexpectedly found zero in fast

How can I catch any mistake, and I mean any type, including fatal errors, exceptions, any type ...
in other languages ​​we will use try, catch, but do, catch does not do the trick when it wraps around null values. but why? really why?

+4
source share
3 answers

You use the do-catch statement to handle errors by running a block of code. If an error occurs in the code in the do clause, it maps to catch clauses to determine which one can handle the error.

Do you use try? to handle the error by converting it to an optional value. If an error was selected during the evaluation of the attempt? expression, the value of the expression is zero. For example, in the following code, x and y have the same meaning and behavior:

func someThrowingFunction() throws -> Int {
    // ...
}

let myValue1 = try? someThrowingFunction()

let myValue2: Int?
do {
    myValue2 = try someThrowingFunction()
} catch {
    myValue2 = nil
}

If someThrowingFunction () throws an error, the value of myValue1 and myValue2 is zero. Otherwise, the value of myValue1 and myValue2 is the value returned by the function. Note that myValue1 and myValue2 are optional for any type of someThrowingFunction (). Here the function returns an integer, so myValue1 and myValue2 are optional integers.

Using try? Allows you to write compressed error handling code if you want to handle all errors the same way. For example, the following code uses several approaches to retrieve data or returns nil if all approaches fail

func fetchData() -> Data? {
    if let data = try? fetchDataFromDisk() { return data }
    if let data = try? fetchDataFromServer() { return data }
 return nil
}

nil, : -

var myValue: Int?


if let checkValue:Int = myValue {
  // run this when checkValue has a value which is not ni
}  
+1

, .

, , :

do {
   let outcome = try myThrowingFunction()
} catch Error.SomeError {
   //do stuff
} catch {
  // other errors
}

:

let outcome = try? myThrowingFunction()

+3

, , Any, guard let if let. do-try-catch nil. unwrap :

public struct UnwrapError<T> : Error, CustomStringConvertible {
    let optional: T?

    public var description: String {
        return "Found nil while unwrapping \(String(describing: optional))!"
    }
}


func unwrap<T>(_ optional: T?) throws -> T {
    if let real = optional {
        return real
    } else {
        throw UnwrapError(optional: optional)
    }
}

:

do {
    isAdsEnabled = try unwrap(dictionary["isAdsEnabled"] as? Bool)
    // Unwrap other values...
} catch _ {
    return nil
}
+3

Source: https://habr.com/ru/post/1625943/


All Articles