Kenneth .J
Kenneth .J

Reputation: 1433

Is it ok to use a catch block to continue code instead of handling an exception?

I have some code that involves checking user input to see if it the input entered is a string or an int, and will execute different code depending on the result. I am using Integer.parseInt in order to determine if the user input is an integer or not, with the NumberFormatException being thrown if it is not.

However, in order to control the flow of the code, i am using a try/catch statement, with the catch block being used to contain code that will be run if the user's input is a string (i.e NumberFormatException) is thrown.

Qn

Is this an acceptable way of using the try/catch block? I've try googling this but all i could find were examples of the catch block being used to handle the Exception thrown instead of it being used as i am doing.

import java.io.*;
import java.util.*;

public class Datafile{

    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Kence\\workspace\\Java 8 - Beyond the Basics - Working Files\\Practice Programs\\src\\Practice Data Edited",true));
        String data = null;
        boolean end = false;
        boolean cont = true;
        String dataEntered = null;
        int menuChoice = printMenu();
        while(!end){
            switch(menuChoice){
                case 1:
                    System.out.println("Please enter a line of data or press 0 to exit back to the main menu");
                    dataEntered = input.nextLine();
                    try {
                        if(Integer.parseInt(dataEntered) == 0){
                            break;
                        }
                    } catch (Exception e) {
                        data += dataEntered + "\n";
                        while(cont){
                            System.out.println("Data entered.Please enter the next line of data or press quit to exit back to the main menu.");
                            dataEntered = input.nextLine();
                            if(Integer.parseInt(dataEntered) == 0){
                                cont = false;
                                break;
                            }else{
                                data+= dataEntered;
                                System.out.println("Current data entered is " + dataEntered);
                            }
                    }


                    }


                    break;

                case 2:
                    System.out.println("2 Entered");
                    break;
                case 3:
                    System.out.println("3 Entered");
                    break;
                case 4:
                    System.out.println("4 Entered");
                    break;
            }//End of switch statement
            menuChoice = printMenu();
        }



        input.close();
    }//End of main



    public static void printStars(){
        for(int i = 0; i<66 ; i++){
            System.out.print("*");
        }
        System.out.println();
    }

    public static int printMenu(){

        printStars();
        System.out.println("System Started");
        printStars();
        System.out.println("Enter 1 to input a new line of data");
        System.out.println("Enter 2 to list all data");
        System.out.println("Enter 3 to save existing data");
        System.out.println("Enter 4 to load data");
        printStars();
        return Integer.parseInt(input.nextLine());
    }

}

Upvotes: 0

Views: 1564

Answers (2)

Anonymous
Anonymous

Reputation: 12080

Exceptions should generally only be used in exceptional cases (see where the name comes from?). They are especially bad in tight loops because the execution overhead is high. Having invalid user input seems like a rather common occurrence, so I would look for another way. Take a look at this answer.

But this all depends on the language. In Python for example, try/catch is the de-facto way of coding (duck-typing).

Upvotes: 0

mjalkio
mjalkio

Reputation: 78

It isn't considered best practices to use a try/catch block for control flow, but it is "acceptable" if you don't care about best practices.

See Determine if a String is an Integer in Java for examples of other ways to check if a number is an integer. You could use one of those examples and then if it is an integer check if it's equal to zero.

Also, in your code it appears your second call to Integer.parseInt(dataEntered) could still throw an exception that would not be caught.

Upvotes: 2

Related Questions