2

Is it possible to try/catch continue doing instructions, even if firts answer is wrong?

For example in the code, if I just type hello instead of true or false, it just goes to the catch part exception. However it is not still running with all other questions. How can I get the program to execute each question, even if one of these throw the InputMismatchException due to a wrong input?

import java.util.InputMismatchException;
import java.util.Scanner;

public class DataTypeJava {
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        try {
            System.out.println("Escribe un dato de tipo boolean opciones son (true/false: ");
            boolean booleanType = scan.nextBoolean();
            System.out.println("Tipo Booleado: " + booleanType);
            System.out.print("Escribe un tipo de dato byte : ");
            byte byteType = scan.nextByte();
            System.out.println("Tipo Byte: " + byteType);
            System.out.print("Escribe un dato de tipo char: ");
            String charType = scan.next();
            System.out.println("Tipo Char: " + charType);
            System.out.print("Escribe un dato de tipo short: ");
            short shortType = scan.nextShort();
            System.out.println("Tipo Short: " + shortType);
            System.out.print("Escribe un dato de tipo int: ");
            int intType = scan.nextInt();
            System.out.println("Tipo Int: " + intType);
            System.out.print("Escribe un dato de tipo long: ");
            long longType = scan.nextLong();
            System.out.println("Tipo Long: " + longType);
            System.out.print("Escribe un dato de tipo float: ");
            float floatType = scan.nextFloat();
            System.out.println("Tipo Float: " + floatType);
            System.out.print("Escribe un dato de tipo double ");       
            double doubleType = scan.nextDouble();
            System.out.println("Tipo Double: " + doubleType);
        } catch (InputMismatchException e) {
            //TODO: handle exception
            System.out.println("Dato ingresado no es correcto");
        }
    }
}
Twenty
  • 5,234
  • 4
  • 32
  • 67
Dave Dve
  • 45
  • 2

4 Answers4

0

You can simply split one big try catch block into multiple smaller ones. This way each question would be executed even if previous have failed.

Alternatively, You would need to create the validation logic for each of the inputs that you are going to accept. Then You could create a methods that would be responsible for accepting or rejecting the input without throwing the exception. But this requires some additional work and using additional methods to verify the data. And You would basically need to accept all data as String and then cast it by Yourself.

Dominik Wosiński
  • 3,769
  • 1
  • 8
  • 22
0

You have two options: • You may use a separate try-catch block for every question. Thus, you can handle each one the way you want.

• You don't use a try-catch block anymore, and handle the input the way you want.

Mohammed Deifallah
  • 1,290
  • 1
  • 10
  • 25
0

You can make an interface and method that required an interface as a parameter like below.

public interface SafeRunInterface {
    void do();
} 

public void safeRun(SafeRunInterface safeRunInterface){
    try
    {
       safeRunInterface.do();
    }
    catch(Throwable e)
    {
       //Print error

       //Call method itself because exception ouccured.
       safeRun(safeRunInterface);
    }
}

So, you can call this method like below.

safeRun(() -> {
  //Do something here.
});

Here is information about lamda and pass function as a parameter. CLICK HERE

Pemassi
  • 612
  • 1
  • 7
  • 20
0

If you use Java 8 you can specify a getInput function as follow that manages user's input in order to:

  • specify only once the common catch logic
  • simplify multiple questions instructions specifying input handle logic via Lambda function
public static void main(String[] args) {
    getInput("Escribe un dato de tipo boolean opciones son (true/false: ", Scanner::nextBoolean, "Tipo Booleado: ");
    getInput("Escribe un tipo de dato byte : ", Scanner::nextByte, "Tipo Byte: ");
    //...other questions
}


/**
 * Goes to get input from stdin
 * @param inputQuestion The input question for user
 * @param inputHandler The user's input handler function
 * @param outputLabel The output label to show to the user
 * @param <T> The generic input object returned by scanner
 */
private static <T> void getInput(String inputQuestion, Function<Scanner, T> inputHandler, String outputLabel) {
    Scanner scan = new Scanner(System.in);
    try {
        System.out.println(inputQuestion);
        System.out.println(outputLabel + " " + inputHandler.apply(scan));
    } catch (InputMismatchException e) {
        //TODO: handle exception
        System.out.println("Dato ingresado no es correcto");
    }
}                                               
gregorycallea
  • 1,218
  • 1
  • 9
  • 28