Catch an Overflow

equation :
let v : Double? = pow(x,y)

this can overflow depending on the values
but how can I CATCH it (it usually returns 0.000000xxxx instead of an error or right answer)

TRY/CATCH doesn’t work (and is documented as such)

SWIFT

That’s an odd thing not to be able to catch. I don’t know Swift, but if I were faced with this in other languages, I’d write a safepow() function that validates the arguments before calling pow() I suppose. Any overhead would probably be less than setting up the stack frame for a try/catch anyway. Calling pow() should not force you to do that to begin with.

I assume you’re wanting to prevent NaN or NegativeInfinity or PositiveInfinity result values? In C# those are just constants on the Double struct that you can test for … it wouldn’t involve a try/catch. The .NET framework calls into the underlying C runtime under the hood (hence results can vary by OS) but unusable values like that can then just be tested for after the call.

It doesn’t look like pow throws.

I readlize it doesn’t throw an exception… That is my problem.

Given X and Y I need to know BEFORE it trys if it will fail, Crashing is not an option

If it returns NAN or INF, I’d be ok, but it doesn’t

Maybe use logaritms to test for overflow before calculating?

( ln(m) / ln(a) ) < b )

where m is the max number for the datatype. For double m = 9007199254740992, I think…
a and b are pow(a,b) parameters.

maybe the approach suggested in this SO thread about converting it into a throwing function ?

that actually is kind of what I ended up doing