Search code examples
javaexceptionnumberformatexception

How to catch java.lang.NumberFormatException.forInputString Exception in Controller?


I have a checkbox in my JSP page that accepts integer values:

<form:checkbox path="somePath" value="2" /> Dangerous Checkbox <br />

If the user changes the value of the input to a String value, e.g.:

<form:checkbox path="somePath" value="blah" /> Dangerous Checkbox <br />

the page will throw a NumberFormatException. How can I catch this in my Controller and show a meaningful message?


Solution

  • you can use JSTL's c:catch tag:

    <c:catch var ="numberFormatException">
    <form:checkbox path="somePath" value="blah" /> Dangerous Checkbox <br />
    </c:catch>
    
    <c:if test = "${numberFormatException!= null}">
       <p>The exception is : ${numberFormatException} <br />
       There is an exception: ${numberFormatException.message}</p>
    </c:if>