Reputation: 629
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
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
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:
Upvotes: 0
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