Maykol Santos
Maykol Santos

Reputation: 13

How to change a parameter if a class exception is thrown in a subclass java

This really seems a weird question but trully I couldn't figure out a better way to ask it. I have made a class called Brand that throws invalid name exception when the name is null or empty, just like this (only the constructor):

public Brand(String name, String producer, String region) throws ExInvalidBrand {
    if (name == null || name.equals("")) {
        throw new ExInvalidBrand("Brand name cannot be empty or null!");
    }
    this.name = name;
    this.producer = producer;
    this.region = region;
}

Now I need to create a subclass out of this, which is supposed to throw the same exception but when thrown, has to change its name to "White Brand". The constructor of the subclass is:

public CommercialBrand(String name, String producer, String region) throws ExInvalidBrand{
    super(name, producer, region);
}

As i see this, i need to use the super keyword so I actually inherit their variables. The subclass throws the Exception as expected when the name is empty.

The only way I know is create a new constructor in the main class that doesn't ask for the name and then calling that one in the subclass, also creating a new private variable name and try/catching the exception in there.

Can it be done with the constructor as i have it right now?

This is a really weird question, I'm happy to clarify anything I can about this.

EDIT: I've noticed that I probably did not explain myself well.

Imagine that we have this psvm:

public static void main(String[] args) throws ExInvalidBrand {
    Brand br = new Brand("brand1", "producer1", "region1"); //here an object is created with the name = brand1, producer = producer1 and region = region1
    CommercialBrand cb = new CommercialBrand("brand1", "producer1" , "region1"); // same as above, but now from the subclass.
    CommercialBrand cbWithNoName = CommercialBrand("", "producer1", "region1"); 
}

This is what I want. When this happens, the object cbWithNoName should be created nonetheless, and give it the name "White Brand" when the exception is thrown. A try/catch before the super, would be great, something like this, if this was possible, which is not, as far as I know.

public MarcaComercial(String name, String producer, String region) throws ExInvalidBrand{
    try {
        super(name, producer, region);
    } catch (ExMarcaInvalida ex) {
        super("WhiteBrand", producer, region);
    }
}

Upvotes: 1

Views: 280

Answers (1)

Abra
Abra

Reputation: 20914

You can use a ternary operator in the call to super() in the CommercialBrand constructor.

public CommercialBrand(String name, String producer, String region) throws Exception {
    super((name == null || name.equals("") ? "WhiteBrand" : name), producer, region);
}

Upvotes: 1

Related Questions