You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理因API返回格式异常导致的java.lang.StringIndexOutOfBoundsException

解决StringIndexOutOfBoundsException避免应用崩溃

问题分析

异常java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 11说明处理后的datetime字符串仅11位,远不足代码预期的最小长度(8位,用于截取年、月、日)。直接调用substring会触发索引越界,根源是API返回格式不符合预期,且代码缺乏前置校验与异常防护。

解决方案

1. 前置校验拦截非法数据

在处理字符串前,先验证输入的有效性,避免无效数据进入后续逻辑:

public void getCameraDateAndTime() {
    Log.i("TAG", "onChanged: " + response);
    // 先判断response是否为空
    if (response == null || response.trim().isEmpty()) {
        Log.w("TAG", "Invalid response: empty or null");
        return;
    }
    String datetime = response.replace(";", "");
    // 确保长度至少满足截取年、月、日的需求(8位)
    if (datetime.length() < 8) {
        Log.w("TAG", "Datetime format invalid, length too short: " + datetime);
        return;
    }
    String mYear = datetime.substring(0, 4);
    String mMonth = datetime.substring(4, 6);
    String mDay = datetime.substring(6, 8);
    Log.i("TAG", "onChanged: " + mYear + " " + mMonth + " " + mDay);
}

2. 异常捕获兜底

即使做了校验,仍可能存在意外情况,用try-catch包裹敏感代码,确保应用不崩溃:

public void getCameraDateAndTime() {
    Log.i("TAG", "onChanged: " + response);
    try {
        String datetime = response.replace(";", "");
        String mYear = datetime.substring(0, 4);
        String mMonth = datetime.substring(4, 6);
        String mDay = datetime.substring(6, 8);
        Log.i("TAG", "onChanged: " + mYear + " " + mMonth + " " + mDay);
    } catch (NullPointerException | StringIndexOutOfBoundsException e) {
        Log.e("TAG", "Failed to parse camera datetime", e);
        // 可添加降级逻辑,比如使用当前系统时间作为默认值
        // Calendar cal = Calendar.getInstance();
        // String mYear = String.valueOf(cal.get(Calendar.YEAR));
        // String mMonth = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        // String mDay = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));
    }
}

3. 正则格式校验(可选)

如果API可能返回多种格式,用正则表达式严格验证是否符合纯数字(含可能的分号分隔)格式:

public void getCameraDateAndTime() {
    Log.i("TAG", "onChanged: " + response);
    if (response == null || !response.matches("\\d+;?\\d*")) {
        Log.w("TAG", "Datetime format does not match expected pattern");
        return;
    }
    String datetime = response.replace(";", "");
    if (datetime.length() < 8) {
        Log.w("TAG", "Datetime length insufficient");
        return;
    }
    String mYear = datetime.substring(0, 4);
    String mMonth = datetime.substring(4, 6);
    String mDay = datetime.substring(6, 8);
    Log.i("TAG", "onChanged: " + mYear + " " + mMonth + " " + mDay);
}

内容的提问来源于stack exchange,提问作者MARSH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:10:47