Regex or Exception Handling?

前端 未结 7 1903
暗喜
暗喜 2021-01-13 06:22

Which one of the following is a better practice to check if a string is float?

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


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 06:27

    If you use parseDouble, you will end up with what Mark said, but in a more readable way, and might profit from performance improvements and bug fixes.

    Since exceptions are only costly when they are thrown, there is only need to look for a different strategy if you

    • expect wrong formats to happen often
    • expect them to fall in a specific pattern which you can catch faster and beforehand

    In the end you will call parseDouble either, and therefore it is considered alright to use it that way.

    Note that your pattern rejects 7. as a Double, while Java and C/C++ don't, as well as scientific notation like 4.2e8.

提交回复
热议问题