1

I note that StringBuilder indirectly implements Appendable.

Appendable.append(CharSequence) throws the checked exception IOException. So how does AbstractStringBuilder.append(CharSequence) get away with not declaring IOException? Consequently, how is it that I never have to worry about IOException when I append to a StringBuilder?

Is this some odd exception just for existing classes that have been retrofitted for Appendable, or am I forgetting part of my basic Java rules?

7
  • Subclasses can indeed get away with throwing different exception: they can either declare not throwing any, or they can declare to throw a subclass of exception declared by their superclass. Commented Aug 1, 2019 at 15:38
  • 4
    I believe a very similar question was asked here. Please check it out! Commented Aug 1, 2019 at 15:39
  • I think it is the opposite, the method in AbstractStringBulder can throw at most an IOException or lower (more specific, subclass of IOException). The JLS 8.4.8.3. Requirements in Overriding and Hiding for that:"... a method declaration m2 in B overrides or hides a method declaration m1 in A. Then: If m2 has a throws clause that mentions any checked exception types, then m1 must have a throws clause, or a compile-time error occurs..." Commented Aug 1, 2019 at 16:01
  • 1
    and "... never have to worry about IOException..." is wrong, if you cast to Appendable you will have to Commented Aug 1, 2019 at 16:05
  • 1
    @M.Prokhorov there is no throws clause of m2... so hard to say which one is more relevant - probably both together Commented Aug 1, 2019 at 16:09

2 Answers 2

0

When implementing an interface you may not throw an exception, so you can the following:

new Appendable() {

    @Override
    public Appendable append(CharSequence charSequence) {
        return null;
    }

    @Override
    public Appendable append(CharSequence charSequence, int i, int i1) {
        return null;
    }

    @Override
    public Appendable append(char c) {
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, you can throw a subclass of exception declared by your superclass/interface.
0

When implementing an interface or extending an abstract class, you can decide whether to throw an exception or not.

An overriding method can throw any unchecked exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.