java中的字符串到字符串 - 可能是坏数据,需要避免异常 [英] String to Int in java - Likely bad data, need to avoid exceptions

查看:84
本文介绍了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.

这篇关于java中的字符串到字符串 - 可能是坏数据,需要避免异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆