Missing catch of NumberFormatException¶
ID: java/uncaught-number-format-exception
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- reliability
- external/cwe/cwe-248
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
Methods such as Integer.parseInt
that parse strings into numbers throw NumberFormatException
if their arguments cannot be parsed. This exception should be caught so that any parse errors can be handled.
Recommendation¶
It is usually best to handle NumberFormatException
in a catch
clause surrounding the call to the parsing method.
Example¶
In the following example, the first call to Integer.parseInt
does not catch the exception. The second call does.
String s = ...;
int n;
n = Integer.parseInt(s); // BAD: NumberFormatException is not caught.
try {
n = Integer.parseInt(s);
} catch (NumberFormatException e) { // GOOD: The exception is caught.
// Handle the exception
}
References¶
Java API Specification: Integer.valueOf, Integer.parseInt, Long.parseLong, NumberFormatException.
Common Weakness Enumeration: CWE-248.