Previously, in Parsing Tokens, we knew how to convert tokens into specific data types that we can use in our code, such as whole numbers, floating-point numbers, and even boolean values.
However, the user might also input a value that cannot be directly parsed into a specific data type, such as inputting hello and parsing it into an integer with nextInt().
This might end our program prematurely, therefore, we could learn how to handle parsing errors that might occur during runtime.
When Do Parse Errors Occur?
There are a couple of ways when parse errors occur, we’ll describe them in this section:
- Input Mismatch Error
- Out of Bounds Error
Input Mismatch Error
Suppose that we have the input stream:
abc
However, your code tries to parse it as an integer using nextInt().
Since, the token is not an integer, the nextInt() method simply throws an error.
In other words, an Input Mismatch error is when the token doesn’t match the structure of a specific data type, that it is unable to parse the token into that data type.
Some other ways when an Input Mismatch error occurs is when:
- A valid input is combined with an invalid input, without separation by a delimiter
- For example, parsing
123ainto an integer with `nextInt().
- For example, parsing
nextBoolean()tries to parse a non-boolean token.- For example, parsing
yesinto a boolean, which is neithertrueorfalse.
- For example, parsing
Out of Bounds Error
Suppose that we have the input stream:
256
However, your code tries to parse it as a whole number, but using the nextByte() method.
Since the byte data type is only valid for numbers between -128 to 127, the method simply throws an error.
In other words, an Out of Bounds error occurs when the numeric data type you’re trying to parse a specific token exceeds the range of the that data type.
Handling Invalid Tokens
When either an Input Mismatch or an Out of Bounds error occur, they usually return the exception `java.util.InputMismatchException.
In that case, we set up a try... catch loop using this exception.
Then, we enclose our token scanner inside the try block.
Inside the catch block, we then place code on what happens if the exception occurs.
public class Main {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
try {
int num;
System.out.print("Enter a number: ");
num = nextByte();
System.out.print("You entered: " + num);
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input");
}
}
}This way, if we type in the input:
Enter a number: 123
The output is:
You entered: 123
But when we enter an invalid input like:
Enter a number: abc
The output is:
Invalid input
Also, this works for out of range inputs as well, so if the input is:
You entered: 129
The output is also:
Invalid input
Tip
Using Package-Defined ExceptionsThe exception
java.util.InputMismatchExceptionis defined in the packagejava.util. Therefore, to use the exception in acatchblock, one may write:catch (java.util.InputMismatchException e) { // ... }However, you can also import the exception class from
java.utilusing this statement:import java.util.InputMismatchException;Then, we can now simply use the exception name without referring to its class name.
catch (InputMismatchException e) { // ... }Alternatively, you can just simply import the entire
java.utilpackage using this statement:import java.util.*;This imports all classes in
java.util, including the exception classjava.util.InputMismatchException.Therefore, we can just simply refer to the exception name instead:
catch (InputMismatchException e) { // ... }This can also work for any exceptions defined in other packages.