Java – regular expression or exception handling?

Which of the following is better to check whether the string is floating?

try{
 Double.parseDouble(strVal);
}catch(NumberFormatException e){
 //My Logic
}

or

if(!strVal.matches("[-+]?\\d*\\.?\\d+")){
 //My Logic
}

In terms of performance, maintenance and readability?

Yes, I want to know which is a good coding exercise?

Solution

Personal opinion - I've seen code, and I hope most developers tend to try - capture blocks Try catch is also more readable in a sense and assumes that in most cases the string will contain significant numbers But there are many things to consider your example, which may affect the effect of your choice

>You often want strings to contain no significant digits. > Note that for batch processing, you should create a pattern object outside the loop This will prevent the code from recompiling the mode every time. > As a general rule, you should never use expectations as a logical process Your try catch represents logic. If it is not a string, your regular expression represents logic if it is a number Therefore, it is not obvious what the context of the code is. > If you choose regular expression technology, you may still need to convert at some point, so in fact, it may be a waste of energy. > Finally, whether the performance requirements of the application are important enough to ensure analysis at this level In general, I recommend keeping it as simple as possible, making it work, and then using some code analysis tools to find bottlenecks and adjust them if there are performance problems

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>