Create an array of characters which will be initialized during run time with vowels.
If user enters any consonant, your code should generate a user-defined checked
exception, InvalidVowelException. The description or message of
InvalidVowelException is "character is consonant". Handle the exception by using
try, catch, finally, throw and throws.
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        try {
            char[] vowelArray = createVowelArray();
            System.out.println("Array created");
        } catch (InvalidVowelException exception) {
            System.out.println(exception.getMessage());
        } finally {
            System.out.println("End of program");
        }
    }
    public static char[] createVowelArray() throws InvalidVowelException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter size of array: ");
        int size = scanner.nextInt();
        char[] vowelArray = new char[size];
        String vowels = "aeiouAEIOU";
        for (int i = 0; i < size; i++) {
            System.out.print("Enter vowel: ");
            vowelArray[i] = scanner.next().charAt(0);
            if (vowels.indexOf(vowelArray[i]) == -1)
                throw new InvalidVowelException("character is consonant");
        }
        return vowelArray;
    }
    static class InvalidVowelException extends Exception {
        public InvalidVowelException(String message) {
            super(message);
        }
    }
}
Comments