Java中的String to Int - 可能是坏数据,需要避免异常

2022-01-17 00:00:00 numbers parsing java

Java 没有可空类型,也没有 TryParse(),如何在不抛出异常的情况下处理输入验证?

Seeing as Java doesn't have nullable types, nor does it have a TryParse(), how do you handle input validation without throwing an exceptions?

通常的方式:

String userdata = /*value from gui*/
int val;
try
{
   val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
   // bad data - set to sentinel
   val = Integer.MIN_VALUE;
}

我可以使用正则表达式来检查它是否可解析,但这似乎也有很多开销.

I could use a regex to check if it's parseable, but that seems like a lot of overhead as well.

处理这种情况的最佳做法是什么?

What's the best practice for handling this situation?

理由:关于异常处理的 SO 讨论很多,普遍的态度是异常应该只用于意外情况.但是,我认为糟糕的用户输入是意料之中的,并不罕见.是的,这确实是一个学术观点.

Rationale: There's been a lot of talk on SO about exception handling, and the general attitude is that exceptions should be used for unexpected scenarios only. However, I think bad user input is EXPECTED, not rare. Yes, it really is an academic point.

进一步

一些答案​​确切地说明了 SO 有什么问题.你忽略了被问到的问题,并回答了另一个与它无关的问题.问题不是询问层之间的过渡.如果数字不可解析,问题不是要返回什么.众所周知,val = Integer.MIN_VALUE;对于这个完全上下文无关的代码片段所来自的应用程序来说,这完全是正确的选择.

Some of the answers demonstrate exactly what is wrong with SO. You ignore the question being asked, and answer another question that has nothing to do with it. The question isn't asking about transition between layers. The question isn't asking what to return if the number is un-parseable. For all you know, val = Integer.MIN_VALUE; is exactly the right option for the application that this completely context free code snippet was take from.

推荐答案

差不多就是这样,虽然返回 MIN_VALUE 有点问题,除非你确定它是用于你本质上用作错误代码.不过,至少我会记录错误代码行为.

That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.

也可能有用(取决于应用程序)记录错误输入以便您进行跟踪.

Might also be useful (depending on the application) to log the bad input so you can trace.

相关文章