问题描述
我有一个项目,我们经常使用 Integer.parseInt()
将 String 转换为 int.当出现问题时(例如,String
不是数字而是字母 a
或其他),此方法将抛出异常.但是,如果我必须在我的代码中到处处理异常,这很快就会变得非常难看.我想把它放在一个方法中,但是,我不知道如何返回一个干净的值来表明转换出错了.
I have a project in which we often use Integer.parseInt()
to convert a String to an int. When something goes wrong (for example, the String
is not a number but the letter a
, or whatever) this method will throw an exception. However, if I have to handle exceptions in my code everywhere, this starts to look very ugly very quickly. I would like to put this in a method, however, I have no clue how to return a clean value in order to show that the conversion went wrong.
在 C++ 中,我可以创建一个方法,该方法接受一个指向 int 的指针,并让该方法本身返回 true 或 false.但是,据我所知,这在 Java 中是不可能的.我还可以创建一个包含真/假变量和转换后的值的对象,但这似乎也不理想.全局值也是如此,这可能会给多线程带来一些麻烦.
In C++ I could have created a method that accepted a pointer to an int and let the method itself return true or false. However, as far as I know, this is not possible in Java. I could also create an object that contains a true/false variable and the converted value, but this does not seem ideal either. The same thing goes for a global value, and this might give me some trouble with multithreading.
那么有没有一种干净的方法来做到这一点?
So is there a clean way to do this?
推荐答案
你可以返回一个 Integer
而不是 int
,返回 null
解析失败.
You could return an Integer
instead of an int
, returning null
on parse failure.
遗憾的是,Java 没有提供一种在内部不抛出异常的情况下执行此操作的方法 - 您可以隐藏异常(通过捕获它并返回 null),但如果您这样做,它仍然可能是一个性能问题重新解析数十万位用户提供的数据.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
这种方法的代码:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
请注意,如果 text
为空,我不确定这会做什么.您应该考虑-如果它代表一个错误(即您的代码很可能传递无效值,但不应传递空值),则抛出异常是合适的;如果它不代表错误,那么您可能应该像处理任何其他无效值一样返回 null.
Note that I'm not sure off the top of my head what this will do if text
is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
最初这个答案使用了 new Integer(String)
构造函数;它现在使用 Integer.parseInt
和一个装箱操作;通过这种方式,小值最终会被装箱到缓存的 Integer
对象中,从而在这些情况下更加高效.
Originally this answer used the new Integer(String)
constructor; it now uses Integer.parseInt
and a boxing operation; in this way small values will end up being boxed to cached Integer
objects, making it more efficient in those situations.
这篇关于封装Integer.parseInt()的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!