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
Shouldn't exception a cover also exception b?
What if anb
is thrown? How would ana
catch that?A
,B
andTest
as the class names.Di
andDj
(i ≠ j) whereDi
is a subtype ofDj
" - 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 classThrowable
or a subclass ofThrowable
")