How throw error in willSet

I have the following code:

public var endpoint: String! {
    willSet { if newValue == nil { throw ErrorCode.NullValue("endpoint") } }
}

But compiler gives me error: Error is not handled because the enclosing function is not declared 'throws'

You should include in a do { try }

enum ErrorCode: Error {
    case NullValue(_ msg: String)
}

func testNil(_ newValue: String?) throws {
    if newValue == nil {
        throw ErrorCode.NullValue("endpoint")
    }
}

public var endpoint: String! {
    willSet {
        do {
            try testNil(newValue)
        } catch ErrorCode.NullValue("endpoint") {
            print("Error: nil")
        } catch {
            print("Error: Unknown error")
        }
//        if newValue == nil {
//            throw ErrorCode.NullValue("endpoint")
//        }
    }
}

If the goal is to actually throw the error out of the setter, that’s not supported.

You can throw from a read-only property getter, but that’s about it. SE-0310 has some discussion of why throwing setters would be tricky to define and implement.

For the example given, one solution would be to change it from a property to explicit getter/setter methods, and those can throw. For example, endpoint() and setEndpoint(_:).

But also reconsider why the property is declared as an implicitly unwrapped optional: String!. That’s still just an optional, so a user may expect that passing nil would be perfectly legal. Should the property actually be declared as non-optional?

I found a solution myself. I need to force unwrap the newValue like below:

willSet {
// this guarantees newValue is not nil
            let _ = newValue!
        }
How throw error in willSet
 
 
Q