-4

I have read that superclass object can point to subclass object but does not know about the content of subclass . Then how can superclass can catch exception of type subclass ?

I am confused here . Please someone help

class abc {
    public static void main(String k[]) {
        try {
            int a = 0;
            int b = 56 / 0;
        } catch (Exception e) {
            System.out.println(" divide by zero ");
        }

    }
}
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
shikhar
  • 135
  • 1
  • 9

3 Answers3

0

ArithmeticException is a subtype of Exception. So, in your catch, what you're saying is "catch everything that is Exception or a subtype of Exception. In this case, that includes ArithmeticException.

Jeremy
  • 22,188
  • 4
  • 68
  • 81
0

These are two independent things. 1st case is that a generic type will not have visibility of the specific type. the second is reverse, where the exception is matched with he specific type and if not found, goes up the class hierarchy to find the next generic type and the next one until one matches.

in this specific scenario, AE is a subclass of E and hence if you don't have AE, it matches to the next generic type up the hierarchy , which is Exception

Ramanan
  • 39
  • 4
0

A superclass doesn't know about it's subclasses. It's the other way around, i.e. a subclass knows about it's direct superclass.

Your catch statement is kind of like an if statement with an instanceof operator:

if (thrownException instanceof Exception) {
    Exception e = (Exception) thrownException;
    System.out.pritnln("divide by zero");
}

The instanceof operator is logically done by getting the class of the object on the left side and checking if it, or any of it's superclasses, is the class on the right side of the operator.

So, as you can see, it's not Exception that knows about ArithmeticException, it's ArithmeticException that knows about Exception, in order for that catch statement to work.

Andreas
  • 154,647
  • 11
  • 152
  • 247