{"record":{"id":"331df06975517621","repo":"Blankj/AndroidUtilCode","slug":"bytesize-shouldn-t-be-less-than-zero","errorCode":null,"errorMessage":"byteSize shouldn't be less than zero!","messagePattern":"byteSize shouldn't be less than zero!","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"lib/utilcode/src/main/java/com/blankj/utilcode/util/ConvertUtils.java","lineNumber":473,"sourceCode":"    public static String byte2FitMemorySize(final long byteSize) {\n        return byte2FitMemorySize(byteSize, 3);\n    }\n\n    /**\n     * Size of byte to fit size of memory.\n     * <p>to three decimal places</p>\n     *\n     * @param byteSize  Size of byte.\n     * @param precision The precision\n     * @return fit size of memory\n     */\n    @SuppressLint(\"DefaultLocale\")\n    public static String byte2FitMemorySize(final long byteSize, int precision) {\n        if (precision < 0) {\n            throw new IllegalArgumentException(\"precision shouldn't be less than zero!\");\n        }\n        if (byteSize < 0) {\n            throw new IllegalArgumentException(\"byteSize shouldn't be less than zero!\");\n        } else if (byteSize < MemoryConstants.KB) {\n            return String.format(\"%.\" + precision + \"fB\", (double) byteSize);\n        } else if (byteSize < MemoryConstants.MB) {\n            return String.format(\"%.\" + precision + \"fKB\", (double) byteSize / MemoryConstants.KB);\n        } else if (byteSize < MemoryConstants.GB) {\n            return String.format(\"%.\" + precision + \"fMB\", (double) byteSize / MemoryConstants.MB);\n        } else {\n            return String.format(\"%.\" + precision + \"fGB\", (double) byteSize / MemoryConstants.GB);\n        }\n    }\n\n    /**\n     * Time span in unit to milliseconds.\n     *\n     * @param timeSpan The time span.\n     * @param unit     The unit of time span.\n     *                 <ul>\n     *                 <li>{@link TimeConstants#MSEC}</li>","sourceCodeStart":455,"sourceCodeEnd":491,"githubUrl":"https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/ConvertUtils.java#L455-L491","documentation":"ConvertUtils.byte2FitMemorySize(long, int) formats a byte count into B/KB/MB/GB. A negative byteSize is physically meaningless for a memory/file size and would format a bogus negative string, so the method rejects it with IllegalArgumentException. The byteSize check runs only after the precision check passes.","triggerScenarios":"Passing a negative long to byte2FitMemorySize — e.g. a File.length() proxy that returns -1 on error, a subtraction that underflows (freeSpace - usedSpace when used > free), or an unset sentinel value of -1.","commonSituations":"Using File.getFreeSpace()/getUsableSpace() which can return -1 on error or for nonexistent paths; arithmetic on disk stats where used exceeds total; defaulting an 'unknown size' field to -1; reading a size from a damaged header.","solutions":["Guard the size at the source: if size < 0, treat it as unknown (e.g. show \"unknown\"/\"—\") instead of formatting it.","Clamp to 0 with Math.max(0, byteSize) when a negative value should be shown as zero bytes.","Verify the File/StatFs you read the size from actually exists and is readable before computing the value passed in.","Distinguish the -1 'error' return contract of getFreeSpace()/length() from real sizes upstream."],"exampleFix":"// before\nString s = ConvertUtils.byte2FitMemorySize(file.getFreeSpace(), 2); // getFreeSpace() may be -1\n\n// after\nlong free = file.getFreeSpace();\nString s = free < 0 ? \"unknown\" : ConvertUtils.byte2FitMemorySize(free, 2);","handlingStrategy":"validation","validationCode":"// Validate byteSize before formatting\nlong byteSize = source.getFreeSpace(); // may be -1\nif (byteSize < 0) {\n    // treat as unknown rather than format\n    return \"unknown\";\n}\nreturn ConvertUtils.byte2FitMemorySize(byteSize, precision);","typeGuard":"// Reject negative sizes at the boundary\npublic static boolean isValidSize(long size) {\n    return size >= 0;\n}","tryCatchPattern":"try {\n    String s = ConvertUtils.byte2FitMemorySize(byteSize, precision);\n} catch (IllegalArgumentException e) {\n    // byteSize was negative; report unknown\n    s = \"unknown\";\n}","preventionTips":["File.getFreeSpace()/getUsableSpace()/length() can return -1 on error — check before formatting.","Clamp computed sizes (e.g. free - used) to >= 0 with Math.max(0, ...).","Use a dedicated 'unknown' display state for sizes whose source is unreliable."],"tags":["validation","convert","formatting","argument-check"],"backgroundTag":null,"analyzedSha":"7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809","analyzedAt":"2026-08-14T02:26:54.956Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}