olgierd olgierd - 1 year ago 61
Java Question

How to find out which variable is throwing an exception?

I'm writing a program that culculates tip and total from bill and tip rate.

public void takeUserInput() {
Scanner sc = new Scanner(System.in);
double billAmount;
int tipRate;

try {
System.out.print("What is the bill? ");
billAmount = sc.nextDouble();
System.out.print("What is the tip percentage? ");
tipRate = sc.nextInt();

tc.calculate(billAmount, tipRate);
} catch (InputMismatchException e1) {
String errorMessage = "Please enter a valid number for the ";
// errorMessage += billAmount or
// errorMessage += tipRate ?

I'm looking for a way to find out which variable throws InputMismatchException, so I can add which variable name into variable errorMessage and print to the screen.

Answer Source

The variable isn't throwing the exception, the evaluation of the right hand side of the variable assignment is, and so there is no information in the exception to say which variable it was about to assign that to had it succeeded.

What you could consider instead is a new method that encompasses the prompting messages and retries:

billAmount = doubleFromUser(sc, "What is the bill? ", "bill");

Where doubleFromUser is:

static double doubleFromUser(Scanner sc, String prompt, String description){
    while(true) { //until there is a successful input
        try {
            System.out.print(prompt); //move to before the loop if you do not want this repeated
            return sc.nextDouble();
        } catch (InputMismatchException e1) {
            System.out.println("Please enter a valid number for the " + description);

You will need a different one for int and double, but if you have more prompts, you will save in the long run.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download