0

I am trying to understand how multiple catch statement works in java. In the documentation, they say that you are not allowed to have related types in catch statement.

Here I have a little sample that I am playing with:

class a extends Exception{}

class b extends RuntimeException{}

public class test{
    public static void main(String[] args){
        try {
            System.out.println(new a() instanceof Exception);
            System.out.println(new b() instanceof Exception);
            throw new a();
        }catch(a | b e) {
            System.out.println(e.getStackTrace());
        }
    }
}

Both classes are instance of Exception. First, one is obvious way and second inherit from RuntimeException and RuntimeExeption inherit Exception.

So why is this code compiling? Shouldn't exception a cover also exception b? Thank you

4
  • 2
    Shouldn't exception a cover also exception b? What if an b is thrown? How would an a catch that?
    – tkausl
    Commented Jan 27, 2020 at 20:46
  • On a side note, you should use A, B and Test as the class names. Commented Jan 27, 2020 at 21:32
  • 2
    I think the specification is a bit more specific: "It is a compile-time error if a union of types contains two alternatives Di and Dj (i ≠ j) where Di is a subtype of Dj " - so nothing about having a common ancestor (wouldn't work because all Exception must be a descendant of Throwable: "Each class type used in the denotation of the type of an exception parameter must be the class Throwable or a subclass of Throwable")
    – user85421
    Commented Jan 27, 2020 at 21:58
  • Please follow the naming conventions. Classes (which your exceptions a and b are) should start with an uppercase character. For exceptions also end with “Exception”. Commented Jan 27, 2020 at 23:22

1 Answer 1

7

By related types I believe the relationship they are referring to is the extends (or subclass) relationship. So in your case you have:

Exception 
├── a
└── RuntimeException
    └── b

a is a subclass of Exception

b is a subclass of RuntimeException which is a subclass of Exception

a is not a subclass of b AND b is not a subclass of a

Therefore the enhanced catch block can catch a and b.

1
  • Yes, Kyle. Now makes sense.
    – Adrian
    Commented Jan 28, 2020 at 6:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.