{"record":{"id":"505d402ca5eafa02","repo":"TheAlgorithms/Java","slug":"cannot-convert-nan-to-long","errorCode":null,"errorMessage":"Cannot convert NaN to long!","messagePattern":"Cannot convert NaN to long!","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"warning","filePath":"src/main/java/com/thealgorithms/maths/MathBuilder.java","lineNumber":29,"sourceCode":" * Date: Oct 20, 2024\n */\npublic final class MathBuilder {\n    private final double result;\n\n    private MathBuilder(Builder builder) {\n        this.result = builder.number;\n    }\n\n    // Returns final result\n    public double get() {\n        return result;\n    }\n\n    // Return result in long\n    public long toLong() {\n        try {\n            if (Double.isNaN(result)) {\n                throw new IllegalArgumentException(\"Cannot convert NaN to long!\");\n            }\n            if (result == Double.POSITIVE_INFINITY) {\n                return Long.MAX_VALUE;\n            }\n            if (result == Double.NEGATIVE_INFINITY) {\n                return Long.MIN_VALUE;\n            }\n            if (result > Long.MAX_VALUE) {\n                return Long.MAX_VALUE;\n            }\n            if (result < Long.MIN_VALUE) {\n                return Long.MIN_VALUE;\n            }\n            return Math.round(result);\n        } catch (Exception ex) {\n            return 0;\n        }\n    }","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/MathBuilder.java#L11-L47","documentation":"Thrown inside MathBuilder.toLong() when the internal result is NaN. IMPORTANT: this exception is immediately caught by the method's own catch (Exception ex) block at line 44, which silently returns 0. The caller never sees the exception; the observable symptom is that toLong() returns an unexpected 0. NaN typically results from operations like sqrt of a negative number, log of a negative, or 0.0/0.0.","triggerScenarios":"Building a MathBuilder whose result is NaN (e.g., via sqrt() on a negative, log() on a negative) and then calling toLong(). The caller gets 0, not the exception. The exception is only visible in a debugger or if the catch block is removed.","commonSituations":"Chaining builder operations that produce NaN without checking intermediate state. Debugging why toLong() returns 0 unexpectedly — the swallowed exception hides the real cause.","solutions":["Check Double.isNaN(builder.get()) before calling toLong() to detect NaN results","Avoid operations that produce NaN: validate inputs to sqrt, log, and division before applying them","Be aware that toLong() silently returns 0 for NaN — do not rely on it to signal errors"],"exampleFix":"// before\nMathBuilder mb = new MathBuilder.Builder(-1.0).sqrt().build();\nlong result = mb.toLong();  // silently returns 0\n\n// after\nMathBuilder mb = new MathBuilder.Builder(-1.0).sqrt().build();\nif (Double.isNaN(mb.get())) {\n    throw new ArithmeticException(\"Result is NaN, cannot convert to long\");\n}\nlong result = mb.toLong();","handlingStrategy":"validation","validationCode":"MathBuilder mb = builder.build();\ndouble value = mb.get();\nif (Double.isNaN(value)) {\n    throw new ArithmeticException(\"MathBuilder result is NaN, cannot convert to long\");\n}\nlong result = mb.toLong();","typeGuard":"static boolean isConvertibleToLong(double value) {\n    return !Double.isNaN(value);\n}","tryCatchPattern":null,"preventionTips":["Always check mb.get() for NaN before calling toLong() — the exception is swallowed internally and toLong() silently returns 0","Avoid operations that produce NaN: sqrt of negatives, log of negatives, 0.0/0.0","Treat toLong() returning 0 as suspicious — it may indicate a swallowed NaN exception"],"tags":["math","nan","swallowed-exception","builder","code-smell"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}