How to catch exception from non-throwing functions?

Viewed 251

Sorry if the question is silly for you. I need to catch overflow exception from power function. I cannot use

do {
   try pow(3, 100)
}
catch {
   .....
}

Xcode shows warning that pow doesn't have throws. If I remove word try from code, then Xcode shows warning that catch is unreachable.

Any idea what can be used?

2 Answers

You can not use error handling for a function that doesn't throw so any combination of try or do/catch will not work

What you can do in this case is to check if the function returns a valid number like

let value = pow(3, 1000)

if value.isNaN {
    //throw error or other error handling
}

You can convert pow to a throwing function if you prefer:

enum NumericError: Error {
    case notANumber
    case infiniteNumber
}

func throwingPow(_ x: Decimal, _ y: Int) throws -> Decimal {
    let v = pow(x, y)
    if v.isInfinite {
        throw NumericError.infiniteNumber
    }
    if v.isNaN {
        throw NumericError.notANumber
    }
    
    return v
}

do {
   try throwingPow(3, 100)
}
catch {
   print(error)
}

This isn't meant to be all possible exceptions, just an example. Making it a throwing function helps with the ergonomics at the call site if you want to force the caller to have to consider all these odd cases as errors.

You can get NaN and infinite value from pow, for example:

let i = pow(Float.infinity, 1)
i.isNaN // false
i.isInfinite // true


let n = pow((0 / 0), 1)
n.isNaN // true
n.isInfinite // false
Related