-2

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("=========================");
        }
    }
}
Kara William
  • 1
  • 1
  • 4

4 Answers4

1

I would check the String, int,... with an if-statement and if something is incorrect throw an IllegalArgumentException.

Tom Jonckheere
  • 1,630
  • 3
  • 20
  • 37
1

First you have to write conditions (i.e. if statements) that check if the input is invalid. When you detect invalid input, you should throw an exception.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can write custom exception like mentioned here.

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

You can give some logical name to your custom exception like IntegerNumberOutofRangeException.

And then you can use if else in your code and throw that custom exception for specific condition you have mentioned.

Code

int intNumber = 50;
if (intNumber > 60 && intNumber < 100) {
    // Do your work
} else {
    throw new CustomException("Integer number out of expected range of 60 to 100");
}
Community
  • 1
  • 1
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
-1

You should use IF to make validations.

A best practice is to not throw an exception from the constructor of a class. Another best practice is to not make validations in the constructor of the class. So a ruff improvement of your code would be (i didn't run it and there are still improvements to be made):

public class CD {
    String artistname = "";
    String albumname = "";
    double cdprice = 0;
    int amountinstock = 0;

    public String ValidationMessage = "";

    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 boolean ValidateCD()
    {
        this.ValidationMessage = "";
        if (/*insert validation condition here*/)
        {
            this.ValidationMessage = "CD IS NOT VALID BECAUSE TITLE IS WRONG";
            return false;
        }
        return true;
    }

    public static void main(final String[] arg) throws Exception {

        final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);

        final boolean isValid = cd1.ValidateCD();
        if (!isValid) {
            System.out.println(cd1.ValidationMessage);
        }

    }
}
David ten Hove
  • 2,748
  • 18
  • 33
Adrian Nasui
  • 1,054
  • 9
  • 10
  • That's an awful 'best practice'. It will allow you to create objects that are invalid according to their own invariants. The validity of the object is dependent on the usage side invoking a second method. Very fragile. In normal scenarios, it's the job of the domain class (CD) to make sure it cannot hold invalid contents. As such, the validation must be done in the constructor and the setters (or use the setters in the constructor, even better). Fail fast. – Joeri Hendrickx Nov 28 '14 at 10:17