Mike
Mike

Reputation: 27

Custom Exceptions String Array

I'm building a custom exception which basically is thrown if an array doesn't contain 5 strings. This is what I have so far. The only exception that really matters is the custom one as I just have to show that that exception is thrown if the array doesn't contain the 5 strings after the input file was split. Any help would be appreciated. Thanks!

package exceptions;

import java.io.File;
import java.util.Scanner;

public class Exceptions {

    public static void main(String[] args) {
        String input, formattedInt, field[];
        int recordNumber = 0;
        int length;
        Scanner inputFile;

        try {
            inputFile = new Scanner(new File("data.txt"));
            while (inputFile.hasNextLine()) {
                recordNumber++;
                formattedInt = String.format("%2d", recordNumber);
                input = inputFile.nextLine();
                field = input.split(",");
                length = field.length;
                if (field.length != 5) throw new CustomException(field.length);
                System.out.println("Record #" + formattedInt + ": " + input);
            }
        } catch (Exception e) {
            System.out.println("Error! Problem opening file.\nError was: " + e);
        } catch (CustomException ce) {
            System.out.println(ce);
        }
    }
}

CustomException.java

package exceptions;

public class CustomException extends Exception {
    private int fieldcount;

    public CustomException(int fieldCount) {
        super("Invalid Count: " + fieldCount);
    }

    public int getCount() {
        return fieldcount;
    }
}

Upvotes: 2

Views: 813

Answers (1)

beresfordt
beresfordt

Reputation: 5222

CustomException extends Exception so any CustomException will be caught in the first catch block.

Rearrange your blocks so the catch(CustomException e) block comes before the catch(Exception e) block

Upvotes: 4

Related Questions