In the sample code below I am dividing by zero which when I step through it with the debugger the (dividend / divisor) yields an Infinity or NaN (if the divisor is zero). When I cast this result to a long I get a valid result, usually something like -9223372036854775808. Why is this cast valid? Why doesn’t it stop executing (throw an exception for example) rather than assign an arbitrary value?
double divisor = 0;
double dividend = 7;
long result = (long)(dividend / divisor);
A cast is valid if it is known at compile time that the conversion might succeed or always succeeds. Casts are only illegal when the conversion cannot possibly succeed. (For example, casting a sealed type to an interface it does not implement.) A conversion from double to long might succeed. Therefore the cast is valid.
Because you didn’t ask for an exception! The spec is extremely clear on what the expected behaviour is. See section 6.2.1:
You’re executing the code in an unchecked context; you asked for no exception so you’re getting no exception. If you want an exception, ask for one; use a checked context.