Eri*_*son 17 java exception try-catch numberformatexception
我遇到这种情况,我需要解析String到int,我不知道该怎么做了NumberFormatException.当我没有抓住它时,编译器不会抱怨,但我只是想确保我正确处理这种情况.
private int getCurrentPieceAsInt() {
int i = 0;
try {
i = Integer.parseInt(this.getCurrentPiece());
} catch (NumberFormatException e) {
i = 0;
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
我想简化这样的代码.编译器没有问题,但线程死了NumberFormatException.
private int getCurrentPieceAsInt() {
int i = 0;
i = Integer.parseInt(this.getCurrentPiece());
return i;
}
Run Code Online (Sandbox Code Playgroud)
Google CodePro希望我以某种方式记录异常,我同意这是最佳做法.
private int getCurrentPieceAsInt() {
int i = 0;
try {
i = Integer.parseInt(this.getCurrentPiece());
} catch (NumberFormatException e) {
i = 0;
e.printStackTrace();
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
我希望此方法0在当前片段不是数字或无法解析时返回.当我没有NumberFormatException明确地捕获时,它是否不分配变量i?或者是否有一些Integer.parseInt()返回的默认值?
一般风格说,如果我捕获异常,我应该在某处记录它.我不想记录它.这个异常有时被抛出是正常的操作,这对我来说也不合适.但是,我找不到一个函数,它会告诉我是否Integer.parseInt()会抛出异常.所以我唯一的行动方式似乎就是调用它并捕获异常.
该javadoc的为parseInt没有太大帮助.
以下是我想知道的具体问题:
Integer.parseInt()会NumberFormatException在调用之前抛出一个?然后我就没有问题记录这个,因为它永远不会发生.AWTEvent.consume().如果是这样,那么我会这样做,以便Google CodePro不会将其视为"未记录".Cam*_*ner 13
可悲的是没有.至少不在核心Java API中.然而,编写一个很容易 - 只需修改下面的代码即可.
如果你没有捕获异常,那么堆栈将展开,直到它遇到将处理它的catch块,或者它将完全展开并停止线程.事实上,变量不会被分配,但这并不是你想要的.
可能有一种方法可以告诉CodePro忽略此特定警告.当然,使用FindBugs和Checkstyle等工具,您可以关闭特定位置的警告.(编辑:@Andy指出了如何做到这一点.)
我怀疑你想要的是@daveb提到的Commons lang包.编写这样的函数非常容易:
int parseWithDefault(String s, int def) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException e) {
// It's OK to ignore "e" here because returning a default value is the documented behaviour on invalid input.
return def;
}
}
Run Code Online (Sandbox Code Playgroud)
在commons lang中有NumberUtils.toInt(String,int),它可以完全按照你的意愿行事.
NumberUtils.toInt("123", 42) ==> 123
NumberUtils.toInt("abc", 42) ==> 42
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70208 次 |
| 最近记录: |