Reputation: 11
I'm trying to learn Java Exception handling. I wrote the following code:
import java.util.*;
public class Problem1
{
static Scanner length = new Scanner(System.in);
public static void main(String[] args)
{
double x;
double y;
System.out.println("Input a length in Feet and than Inches.");
x = length.nextDouble();
y = length.nextDouble();
try
{
System.out.println("Feet - Inches:" + x * 12);
System.out.println("Inches - Centimeters:" + y * 2.14);
}
catch (InputMismatchException imeRef)
{
System.out.println("Do not use letters" + imeRef.toString());
}
}
}
The program simply converts inputs in Feet and Inches to just Inches. I try to break it by giving it an input of:
-1
e
The program breaks but I'm not properly catching and handling the exception. Any ideas what I'm doing wrong?
Thanks
Upvotes: 0
Views: 251
Reputation: 311
A catch statement only catches exceptions that are thrown in its corresponding try block.
This is what you want. This prompts the user for each question, one at a time, and resets and asks again on bad input. Note the length.next() in the catch - that's needed to avoid an infinite loop - you have to advance past that bad token.
while (true) {
try {
System.out.println("Input a length in feet");
double x = length.nextDouble();
System.out.println("Input a length in inches");
double y = length.nextDouble();
System.out.println("Feet - Inches:" + x * 12);
System.out.println("Inches - Centimeters:" + y * 2.14);
break;
}
catch (InputMismatchException imeRef) {
System.out.println("Do not use letters" + imeRef.toString());
// need to purge the bad token
length.next();
}
}
Upvotes: 1
Reputation: 3197
You do not catch exception is because the exception is thrown when calling length.nextDouble() for variable x and y.
x = length.nextDouble();
y = length.nextDouble();
But You do not put them in try - catch code. Put the above 2 line code to try - catch, you will catch the exception.
Upvotes: 1
Reputation: 29166
Put the following two lines -
x = length.nextDouble();
y = length.nextDouble();
inside your try
block -
try {
x = length.nextDouble();
y = length.nextDouble();
System.out.println("Feet - Inches:" + x * 12);
System.out.println("Inches - Centimeters:" + y * 2.14);
}
catch (InputMismatchException imeRef) {
System.out.println("Do not use letters" + imeRef.toString());
}
A catch
block only catches the matching exceptions thrown by the statements inside of its corresponding try
block.
Upvotes: 1
Reputation: 45060
You need to move the 2 input statements which read the input from the user into the try
block. The error will be thrown only when the input is read and to handle that in the catch, these statements need to be in the try
block because the catch will handle only the exceptions thrown in its corresponding try
block.
try {
x = length.nextDouble(); // moved inside try
y = length.nextDouble(); // moved inside try
System.out.println("Feet - Inches:" + x * 12);
System.out.println("Inches - Centimeters:" + y * 2.14);
}
Upvotes: 2