I have a class that extends another class (In this case, it's an Exception):
public class NewTypeException extends Exception {
private String exceptionField;
public String getExceptionField() {
return exceptionField;
}
public void setExceptionField(String exceptionField) {
this.exceptionField = exceptionField;
}
public NewTypeException(String cause, String reason) {
super(cause);
exceptionField = reason;
}
}
And another class (for sake of example, lets call this PrintUtil
) that has two methods with similar signatures, the only difference being the Exception type changes to the subclass:
void doStuff(Exception ex) {
System.out.println(ex.getMessage());
}
void doStuff(NewTypeException ex) {
System.out.println("New Type Exception");
System.out.println(ex.getExceptionField());
System.out.println(ex.getMessage());
}
In a lot of places in my code, I have a bunch of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
After adding this new exception type, I want to have this line call the most specific method it can, depending on the argument. However, it seems when I test this, this will only use the method for Exception
even if the runtime type fits another method (e.g. NewTypeException). Is there any way to do this other than replace hundreds of sections of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
with
try {
// code
} catch (NewTypeException ex) {
printUtil.doStuff(ex);
} catch (Exception ex) {
printUtil.doStuff(ex);
}
? This seems like something really basic a OOP language should be able to do...