预期时处理NumberFormatException的正确方法是

预期时处理NumberFormatException的正确方法是

本文介绍了在预期时处理NumberFormatException的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这种情况,我需要解析一个 String 到一个 int 中,不知道该如何处理 NumberFormatException 。编译器没有抱怨,当我没有抓住它,但我只是想确保我正确地处理这种情况。

I'm running into this situation where I need to parse a String into an int and I don't know what to do with the NumberFormatException. The compiler doesn't complain when I don't catch it, but I just want to make sure that I'm handling this situation properly.

private int getCurrentPieceAsInt() {
    int i = 0;
    try {
        i = Integer.parseInt(this.getCurrentPiece());
    } catch (NumberFormatException e) {
        i = 0;
    }
    return i;
}

我想简化我的代码。编译器没有问题,但线程在 NumberFormatException 上死亡。

I want to just simplify my code like this. The compiler doesn't have a problem with it, but the thread dies on the NumberFormatException.

private int getCurrentPieceAsInt() {
    int i = 0;
    i = Integer.parseInt(this.getCurrentPiece());
    return i;
}

Google CodePro要我以某种方式记录异常,我同意这是最佳实践。

Google CodePro wants me to log the exception in some way, and I agree that this is best practice.

private int getCurrentPieceAsInt() {
    int i = 0;
    try {
        i = Integer.parseInt(this.getCurrentPiece());
    } catch (NumberFormatException e) {
        i = 0;
        e.printStackTrace();
    }
    return i;
}

我想要这种方法返回 0 当当前片段不是数字或不能被解析时。当我没有明确地看到 NumberFormatException 时,是否没有分配变量 i ?或者有一些默认值, Integer.parseInt()返回?

I want this method to return 0 when the current piece is not a number or cannot be parsed. When I don't catch the NumberFormatException explicitly, does it not assign the variable i? Or is there some default value that Integer.parseInt() returns?

一般风格说如果我抓到例外,我应该在某个地方登录。我不想登录。有时会抛出这个异常的正常操作,这也不适合我。我找不到一个函数,但是如果 Integer.parseInt()将抛出一个异常。所以我唯一的行动方式似乎是只是调用它并捕获异常。

General style says that if I catch an exception, I should log it somewhere. I don't want to log it. It's normal operation for this exception to be thrown sometimes, which also doesn't sit well with me. I cannot find a function, however, which will tell me if Integer.parseInt() will throw an exception. So my only course of action seems to be to just call it and catch the exception.

parseInt / dev /没有帮助。

The javadoc for parseInt doesn't help much.

以下是我想知道的具体问题:

Here are the specific questions I'd like to know:

推荐答案