Reputation: 4369
i've found this line of code got error if the input not an number
int sum = Integer.parseInt(request.getParameter("sum"));
the error message is
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "a"
root cause
java.lang.NumberFormatException: For input string: "a"
how to handle the input if the input is a string or null?
thanks
Upvotes: 1
Views: 4948
Reputation: 1523
Try:
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch (NumberFormatException e) {
// sum = 0. If you needed to do anything else for invalid input
// put it here.
}
Upvotes: 2
Reputation: 12883
I see the org.apache.jasper.JasperException
Which means this is in a JSP? If you're adding code like that to a JSP, you might want to reconsider what you're doing. Ideally, you should handle things like input validation in a controller of some sort, and then pass off results to a template of JSP for rendering.
There are many frameworks out there to help with this sort of thing, and in general they're worth using because your web application will benefit from all of the work that the framework authors have already done in the realm of security etc...
Pretty much any of the half a dozen code answers already posted will work for you though if you just want to hack it out.
Upvotes: 1
Reputation: 425368
Here's a different approach that doesn't involve throwing and catching exceptions:
String input = request.getParameter("sum");
// Validate the input using regex
if (input == null || !input.matches("^-?\\d{1,8}$")) {
// handle bad input, eg throw exception or whatever you like
}
int sum = Integer.parseInt(input);
Note that this regex doesn't allow numbers too large, and allows negative numbers
Upvotes: 1
Reputation: 1785
Check for null before Using Intefer.parseInt and also you can check whether input contains other than numeric value
Upvotes: 1
Reputation: 9340
Try this:
try {
sum = Integer.parseInt(request.getParameter("sum"));
} catch (NumberFormatException e) {
... // handle if the string isn't a number
} catch (NullPointerException e) {
... // handle if it's null
}
Upvotes: 1
Reputation: 786091
You should first make sure request parameter is not null and contains numbers only using:
if (request.getParameter("sum") != null &&
request.getParameter("sum").matches("^\\d+$"))
int sum = Integer.parseInt(request.getParameter("sum"));
Upvotes: 3
Reputation: 2797
It really depends on what should be done if sum is not a number.
try{
int sum = Integer.parseInt(request.getParameter("sum"));
}
catch(Exception e)
{
//how do you want to handle it? like ask the user to re-enter the values
}
Upvotes: 1
Reputation: 93090
Just catch the exception and handle it accordingly:
int sum;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch {
//do something if invalid sum
}
Upvotes: 1