我是否必须捕获NumberFormatException试图将值解析为int或long?

问题描述 投票:0回答:1

说我有这个方法:

    public long getLongId(JWTClaimsSet claimsSet)
    {
        return Long.parseLong(String.valueOf(claimsSet.getClaim(LONG_ID_CLAIM)));
    }

    public int getIntId(JWTClaimsSet claimsSet)
    {
        return Integer.parseInt(String.valueOf(claimsSet.getClaim(ID_CLAIM)));
    }

对于这两个方法,如果我不发送有效的int或long,我希望该方法返回默认值0。我是否需要在此处捕获NumberFormatException或在内部进行处理?

java
1个回答
0
投票

如果不确定是什么类型的数据类型,则来自JWTClaimsSet ClaimsSet:

 public long getLongId(JWTClaimsSet claimsSet) {
    try {
        return Long.parseLong(String.valueOf(claimsSet.getClaim(LONG_ID_CLAIM)));
    } catch (NumberFormatException e) {
        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}


public int getIntId(JWTClaimsSet claimsSet) {
    try {
        return Integer.parseInt(String.valueOf(claimsSet.getClaim(ID_CLAIM)));
    } catch (NumberFormatException e) {
        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
© www.soinside.com 2019 - 2024. All rights reserved.