0

Is it possible to extend an already existing class to throw an exception? For example, is it possible to create an exception for the following code if the entry already exists? (I am unable to modify the class hence why I need to extend and have to include error handling rather than just displaying messages..)

Entry class:

public Entry(String paramString1, String paramString2, String paramString3, String paramString4, String paramString5)
  {
    this.firstName = paramString1;
    this.lastName = paramString2;
    this.street = paramString3;
    this.town = paramString4;
    if (paramString5.matches("[A-Z]{2}[0-9]{1,2} [0-9]{1,2}[A-Z]{2}")) {
      this.postCode = paramString5;
    } else {
      System.err.printf("Bad postcode: '%s'\n", new Object[] { paramString5 });
      this.postCode = "???";
    }
  }

AddressBook class:

public String add(Entry paramEntry)
  {
    if (paramEntry == null)
      return "Error: null entry";
    if (this.data.contains(paramEntry)) {
      return "Error: this entry already in the book";
    }
    boolean bool = this.data.add(paramEntry);
    if (bool) {
      return " entry added";
    }
    return "entry could not be added";
  }

I have searched the internet and found the following easy to follow websites: http://www.tutorialspoint.com/java/java_exceptions.htm http://www.c-sharpcorner.com/UploadFile/433c33/defining-your-own-exception-class-in-javacustom-exception/

Is this what I need to be doing? (new to java sorry)

ToniHopkins
  • 369
  • 3
  • 11
  • 30

6 Answers6

2

First question you might want to ask yourself, 'do I really want to throw an Exception for this?'. An exception should only be used for events that should never happen, like an IOException. I would just use a Validator to validate user input.

Menno
  • 12,175
  • 14
  • 56
  • 88
  • 1
    That's true. Exceptions are for exceptional conditions only. Invalid user input should be handled by validating it properly. – Kai Apr 29 '13 at 12:27
  • But there is a constraint that parent class cannot be changed (and its methods' signatures) therefore there is no place to add return value from validators (without wrapping it into an unchecked exception) – denis Apr 30 '13 at 20:31
  • Well throwing Exceptions would lead to changes too. E.g. `throws Exception`. That's just reasoning with a double standard. – Menno Apr 30 '13 at 20:52
  • Another thing to add, this really isn't the kind of situation to use an unchecked exception. OP is trying to handle invalid input (or a result derived from invalid input) and thus needs to catch an exception if that's the implementation he will be using. That sounds like a checked exception to me. – Menno Apr 30 '13 at 21:00
  • @aquillo I emailed my tutor to say I had finished my program and was checking through the marking scheme to ensure I had included everything but it mentions to use error handling including exceptions however I was confused as to where to put these as I use IF statements to check the user inputs in the GUI class and couldnt understand where to put exceptions if we are not allowed to modify the AddressBook and Entry classes. His reply was "Use exceptions whenever needed. Exceptions can also be used for validation checks." I guess to gain the marks im going to have to use it for the validation =( – ToniHopkins May 01 '13 at 09:00
  • Ok, no problem. Seems to be the requirement on the program. I'd write a custom exception with a representative name that `extends Exception`. – Menno May 01 '13 at 09:03
  • @Aquillo not good that they would teach us to do things that are bad practice – ToniHopkins May 01 '13 at 09:09
  • Well, it's not widely known as a bad practice. I've had this discussions multiple times. That's why I've created a [question](http://stackoverflow.com/questions/16315564/best-practice-throwing-exception-or-using-validator-on-user-input) solely for this discussion. – Menno May 01 '13 at 09:16
1

No, you cannot override a class and add (checked) exceptions to the signature that is not present in the super class. So you can't subclass AddressBook and override add() to declare a new checked exception. In your case, I wouldn't even suggest to override the add method, since It's fundamentally wrong IMHO. Returning a String (which essentially is a validation error) from an add method is not something I would recommend. If you really want to use exceptions in this case, you could override the method and throw an instance of RuntimeException. But it would really just be lipstick on the pig.

NilsH
  • 13,705
  • 4
  • 41
  • 59
  • You were right. Thanks for pointing out the problem with my answer. I deleted it already. :) Yes, you can't introduce checked exceptions in an override and I forgot about that. :) +1 for you. – Jops Apr 30 '13 at 03:56
1

You can try using sume subclass of RuntimeException.

In this case parent class' method signature will stay the same yet you can throw this exception in subclass.

For example, exception code:

public class MyException extends RuntimeException
{
    public MyException(String message)
    {
        super(message);
    }
}

And then Entry class:

public Entry(String paramString1, String paramString2, String paramString3, String paramString4, String paramString5)
{
    this.firstName = paramString1;
    this.lastName = paramString2;
    this.street = paramString3;
    this.town = paramString4;
    if (paramString5.matches("[A-Z]{2}[0-9]{1,2} [0-9]{1,2}[A-Z]{2}")) {
        this.postCode = paramString5;
    } else {
        throw new MyException(String.format("Bad postcode: '%s'\n", new Object[] { paramString5 }));
    }
}

You will need to handle the exception somewhere:

try
{
    /* create entry etc. */
}
catch(MyException e)
{
    /* ... */
}

Since neither Entry nor AddressBook in your sample actually extend anything I assumed your Entry is a subclass.

AddressBook can be changed in a similar way.

Please note that this is workaround for your inability to change the parent class. I would use a checked exception if it was possible to change your parent class.

denis
  • 417
  • 3
  • 8
0

After you extended class and overriden required method you can check returned value or updated field to take decision if exception is to be thrown, something like:

public String add(Entry paramEntry) //overridden 
  {

    String val = super.add(paramEntry); //call actual method

   if(val.equals("entry could not be added")) //check for exception condition
       throw new OperationException(val);//runtime exception

    return val;
  }

public class OperationException extends RuntimeException {

    public OperationException() {
        super();
    }

    public OperationException(String message, Throwable cause)  {
        super(message, cause);
    }
    public OperationException(String message){
        super(message);
    }

    public OperationException(Throwable cause)  {
        super(cause);
    }
}
harsh
  • 7,502
  • 3
  • 31
  • 32
0

first of all extending class is not related to throwing exceptions.If what you want to know is whether you can throw an exception where the super method does not throw any exceptions then the answer is no.how to override when exceptions are there

Community
  • 1
  • 1
Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50
  • Sort of true. You can always throw an unchecked exception - subclasses of Error or RuntimeException. – emory Apr 29 '13 at 13:20
0

When you extend a class, you need to adhere to the Liskov principles of substitution.

Concretely that means that in any situation where a user can use an object of type Parent, he must be able to use an object of type Child as well.

Clearly you will see that adding a (checked) exception violates this. If the client class was using the Parent class, it did not have a throw clause nor a try/catch for your exception. So if he were to swap with the Child class, the code would become invalid.

So, no, you can't.

You can add a RuntimeException, but it would still be a bad idea.

see http://en.wikipedia.org/wiki/Liskov_substitution_principle

Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53