What Exception to use for FileWriter

Question!

I have a program that allows a user to write information to a file. It doesn't write over everything in the original file, but adds to it. The thing is if the user doesn't enter enough info the programs crashes.

Each line in the text file looks something like this:

info 1, Info 2, info 3, info 4, info 5, info 6, info 7

Every line has six commas and seven pieces of information. So, I need to know what kind of exception to use to prevent a crash if say the user only enters 4 pieces of information or only uses two commas, etc. Anybody know how to do that?

Here's my code:

private void addDVDButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    FileWriter fWriter = null;
    BufferedWriter writer = null;
    try {
        fWriter = new FileWriter("info.txt", true);
        writer = new BufferedWriter(fWriter);

        writer.write(JOptionPane.showInputDialog(this, "ADDING INFO"));
        writer.newLine();
        writer.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this,"More information required");
    }
}                        
By : rjdelight


Answers

How would I verify it though? This is what I am stuck on.

For example by using String.split(",") which will give you a String[], on which you can check if String[].length == 7.

edit: just to make sure this is not a complete solution to your problem, but a good starting point. I strongly agree with all the other comments/answers, throwing an exception is overkill.

edit 2: Let's assume that the user gave the following string as an input, and you want to validate it before writing out to the file:

String str = "a1,b2,c3,d4,e5,f6";

as you can see this string has six elements and five commas, in other words it should give a warning to the user. A very simple way of checking this would be:

if (str.split(",").length != 7) // checks if the string is comma delimited and has seven pieces of information
    warnUser();   // whatever you want to do to warn user
else 
    writeToFile(str);

note that this just shows the principle, in your case you might (and probably will) want to check for other things like formatting, or that you have alpha-numeric text and no underscores or whatever. If you have a lot of conditions you want to check for, you can write a method validateInput(str) which could be a series of condition checks and returns true only if all conditions check out.

By : posdef


Do not throw an exception. Validate the user input and only write it to the file if it is valid.

By : Oswald


This video can help you solving your question :)
By: admin