EeveeLover
EeveeLover

Reputation: 89

Java Exception Handling Specificity

I think it's easier to explain my question if I show my code first, so here it is:

import java.util.Scanner;
public class a{
    public static void main(String[]args){
        Scanner s = new Scanner(System.in);
        System.out.print("Enter either a, b, or c: ");
        try{
            String a = s.nextLine();
            if (!a.equalsIgnoreCase("a")&&!a.equalsIgnoreCase("b")&&!a.equalsIgnoreCase("c")){
                throw new IllegalArgumentException();
            }
            System.out.print("Entered letter: "+a);
        }
        catch (IllegalArgumentException b){
            System.out.println("Invalid input. Only enter a, b, or c.");
        }
    }
}

My question is, is there a way to make three(3) different catch statements in order to specify in the error message that the user entered

  1. another letter other than a, b, or c;
  2. a non-letter character (number or symbol) OR
  3. a blank space?

The thing that crossed my mind for the number error was NumberF

Upvotes: 2

Views: 116

Answers (1)

Nicholas K
Nicholas K

Reputation: 15423

Rather than creating three separate catch blocks you can modify your catch to :

try {
    String a = s.nextLine();
    if (!a.equalsIgnoreCase("a") && !a.equalsIgnoreCase("b") && !a.equalsIgnoreCase("c")) {
        throw new IllegalArgumentException(a);                 // observe this
    }
    System.out.print("Entered letter: " + a);
} catch (IllegalArgumentException ex) {
    String input = ex.getMessage();

    // check for spaces
    if (input.trim().length() == 0) {
        System.out.println("Only black spaces entered");
    } 

    // check for numeric/special characters
    else if (input.matches("^[0-9!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]*$")) {
        System.out.println("User entered a non-letter character (number or symbol)");
    } 

    // check if it isn't a, b or c
    else if ((!input.trim().matches("a|b|c"))) {
        System.out.println("User entered value other than a, b or c");
    }
}

Observe here:

  1. We are including the input entered by the user while throwing the exception
  2. In the catch block we are fetching the value entered by the user and then based on some if conditions printing out the desired exceptions.

You can tweak the conditions within the catch logic as per your convenience, I hope you get the idea behind it. Also, you can create a separate method for handling the exception and call it from the catch block.

Upvotes: 2

Related Questions