John Steed
John Steed

Reputation: 629

Superclass handling subclass exceptions

Let's say I have a superclass called ApplicationDao and a number of inheriting subclasses such as UserDao, ProductDao etc...

If my catch and finally blocks are exactly the same for all my subclasses' CRUD methods, is it possible for the superclass (ApplicationDao) to handle the exceptions rather than the subclasses. That would mean I would only need to write one TRY...CATCH...FINALLY block in the superclass rather than duplicating it in each subclass.

If it is possible, I'm not sure how to do it because the methods in each subclass would have a different name (getUsers in UserDao, getProducts in productDao, etc...) so I'm not directly overriding a method in the superclass.

Any advice appreciated for how to capture exceptions in the parent class for all subclasses.

Upvotes: 0

Views: 4208

Answers (3)

rob
rob

Reputation: 1286

Have your common processing in ApplicationDao and have subclasses call the super class - this way you only write the code for the common stuff once:

public class ApplicationDao {

    public String process() {
        try{
            // Common processing here
        } catch (Exception e) {
            //...
            return "KO";
        }
        return "OK";
    }
}

public class UserDao extends ApplicationDao  {

    public String getUser() {
        String a = super.process();
        // Specific processing here...
        return "user";
    }
}

I would make ApplicationDao abstract...

Upvotes: 1

Teddy
Teddy

Reputation: 4223

Super class cannot 'handle' subclass Exceptions. Subclass can replace/wrap super class methods, not the other way round.

However, you could refactor your code into pieces:

  1. Common functionality like executing a select statement could be moved to a method like executeQuery.
  2. This can be made available in the base class. The subclasses could use this base class method, just passing the appropriate sql query to that method.
  3. In this case, the executeQuery method could handle exceptions like SQLException and wrap them into an application specific unchecked exception (or handle the exception silently if that is acceptable).

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

First, don't give the methods different names. Next, if you make your Superclass abstract, and add one one abstract method (e.g. getObjects() below) then you can catch the Exception(s) thrown in your concrete implementations in one place. Also, you give a caller a single consistent entry point (e.g. getValues()). Note: This can make debugging difficult.

public List<T> getValues() {
  try {
    return getObjects();
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    System.out.println("In finally");
  }
  return null; // <-- there was an Exception. Default return.
}

protected abstract List<T> getObjects()
    throws Exception;

Upvotes: 1

Related Questions