What exception should be used in Java when a file can be read but the file's data is improperly formatted?

StackOverflow https://stackoverflow.com/questions/21666291

  •  09-10-2022
  •  | 
  •  

Question

When a specified file has been read successfully, but the data within the file is improper, such as malformed XML, or an ini file that specifies the wrong variables or is missing a section, or something like that, what should of exception should be used in that case?

Does it make sense to use an IOException with a detailed exception message, or should another kind of exception be used? There doesn't appear to be a good exception type for this sort of event within the standard library.

Was it helpful?

Solution 2

This is a style question as 'technically' it doesn't matter what type of exception you throw; it could be a java.awt.FontFormatException, javax.management.modelmbean.XMLParseException or even just a standard java.lang.Throwable with whatever extra info you put in it.

That being said, as others have suggested, it's probably a better choice to 'roll your own':

public class InvalidFormatting extends java.lang.Throwable
{
    /** The underlying error of this instance */
    public final static String Error = "An invalid format has been detected";

    /** Create a new {@code InvalidFormatting} exception */
    public InvalidFormatting() {
        super(InvalidFormatting.Error);
    }

    /**
     * Create a new {@code InvalidFormatting} exception with additional information
     *
     * @param additionalMsg The additional information to append
     */
    public InvalidFormatting(String additionalMsg) {
        super(InvalidFormatting.Error + "\n" + additionalMsg);
    }
}

Then it can be used as such

throw new InvalidFormatting("here's some extra info");

Hope that can help.

OTHER TIPS

Don't use IOException -- the file has been opened and read successfully; the problem is its content. You could throw an IllegalArgumentException, or create your own exception type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top