I wrote an abstract class "Card" with two child classes called "Sticker" and "PlayingCard". The class "PlayingCard" has an object of an enum called "Color" attribute that basically says what type of card it is (hearts, spades, ...). In this enum, i have a method that returns an object based on a string: if i pass it the string "spades", it'll return an object that contains SPADES. If the string being passed to it doesn't exist as a card type (so not hearts, spades,...), it throws a self made "TypeUnknownException". This exception just calls its super(String message).
Now, when in a different class that reads a file and makes Card objects:
Card c= (Card) Class.forName(one).getConstructor(String.class, double.class).newInstance(two, three);
With one being a string from the txt file (that always will be an implemented class name like Sticker or Playingcard, two being a string taken from the txt file (should be a type of card like spades, but can be different, which should throw the exception, with this string as the message) and three being a parsed double from the txt file.
This would either call the constructor from Sticker or PlayingCard. When it calls the constructor from PlayingCard, it should be able to throw my "TypeUnknownException", so i can catch it to add it to a string of error messages to print out at the end. However, when i try to catch that exception, the compiler says it's never thrown. I get that it's because it doesn't yet know that it can call a constructor that throws my exception, but is there a way to catch that, and only that exception (no catch all, it has to throw other exceptions)?
For reference: code in the PlayingCard class:
public PlayingCard(String col, double worth) throws TypeUnknownException{
this(col,(int)worth);
}
PlayingCards only take ints as its worth, but since the class Card has to take a double, there's the above extra constructor
public PlayingCard(String col, int w) throws TypeUnknownException{
this.color= Color.getColorWithName(col.toUpperCase());
this.worth= w;}
and the getColorWithName method in the enum Color:
public static Color getColorWithName(String name) throws TypeUnknownException{
if(name.equalsIgnoreCase("Spades")){return SPADES;}
else if(name.equalsIgnoreCase("Hearts")){return HEARTS;}
else if(name.equalsIgnoreCase("Clovers")){return CLOVERS;}
else if(name.equalsIgnoreCase("Tiles")){return TILES;}
else throw new TypeUnknownException(name);
}
Something else that might be helpful: When i added a print in the constructor of the exception, it was able to print the name of the type of card that doesn't exist. So the exception is definitely being thrown, i just don't know how to catch it.
Aucun commentaire:
Enregistrer un commentaire