I'm supposed to write exceptions to prevent invalid objects, such as Strings having no blanks or the double and int numbers being in a certain range. I am really confused on how to do this. Am I supposed to use an if/else statement? Or more try/catch statements?
EDIT: Each object needs to be validated. The strings cannot have blanks or contain only blanks, and the numbers cannot be less than zero. There are five other try/catch statements but I only included one. My question is what would I write so that the exception output is different for the different problems and is there a way to write it to avoid writing each exception for each separate try/catch? I looked at other posts about writing exceptions but I haven't learned what super is or does and cannot use it.
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public static void main(final String[] arg) throws Exception {
try {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
System.out.println(cd1.toString());
System.out.println("=========================");
} catch (final CDException cde) {
System.out.println(cde.getMessage());
System.out.println("=========================");
}
}
}