How to avoid Number Format Exception in java?

ashishjmeshram picture ashishjmeshram · Mar 31, 2011 · Viewed 113.7k times · Source

In my day to day web application development there are many instances where we need to take some number inputs from the user.

Then pass on this number input to may be service or DAO layer of the application.

At some stage since its a number (integer or float), we need to convert it into Integer as shown in the following code snippet.

String cost = request.getParameter("cost");

if (cost !=null && !"".equals(cost) ){
    Integer intCost = Integer.parseInt(cost);
    List<Book> books = bookService . findBooksCheaperThan(intCost);  
}

Here in the above case I have to check if the input is not null or if there is no input (blank) or sometimes there is a possibility of a non number inputs e.g. blah, test etc.

What is the best possible way of handling such situations?

Answer

RoflcoptrException picture RoflcoptrException · Mar 31, 2011

Just catch your exception and do proper exception handling:

if (cost !=null && !"".equals(cost) ){
        try {
           Integer intCost = Integer.parseInt(cost);
           List<Book> books = bookService . findBooksCheaperThan(intCost);  
        } catch (NumberFormatException e) {
           System.out.println("This is not a number");
           System.out.println(e.getMessage());
        }
    }