javatry-catchjava.util.scannerinputmismatchexception

Why does this try statement use the catch statement?


import java.util.Scanner;
import java.util.InputMismatchException;
public class bank {
    public static void login() {
        double balance;
        try {
            boolean subtract;
            boolean amounttaken;
            // This is to see if you want to withdraw money
            System.out.println("Do you want to withdraw money?");
            Scanner SCaddOrWithdraw = new Scanner(System.in);
            subtract = SCaddOrWithdraw.nextBoolean();
            if (subtract) {
                System.out.println("How much would you like to withdraw?");
                Scanner SCamounttaken = new Scanner(System.in);
                amounttaken = SCamounttaken.nextBoolean();
                System.out.println("Subtract");
            } else if (!subtract) {
                System.out.print("Ask for bal");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input");
        }
    }
}

I have added a try statement and in the first part of the if I tell it to print subtract but instead it calls the catch statement. Can someone please help? Please keep in mind that I am a beginner in coding.


Solution

  • It is a complete structure.

    try {
        // Statement Which May Throw Exceptions
    } catch(Exception e) {
        // If any statement throws the exception
        // Do alternative flow here
    }
    

    If your code within the try block may throw exception, you can do the alternate of it. Like in your above code, if anyone input a string instead of boolean it will throw InputMismatchException, which will be captured in catch block and you can print the error message to user nice and neatly. :)