Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

own exception class hierarchy compile error

i was trying following program


package catchingexceptionhierarchycompileerror;

class MyParentException extends Exception {
}

class MyChildException extends MyParentException {
}

public class Main {
   
    public static void main(String[] args) {
        try {
            throw new MyChildException();
        } catch (MyParentException s) {
            System.err.println("Caught MyParentException");
        } catch (MyChildException a) {   // Compile error expected
            System.err.println("Caught MyChildtException");
        }
    }
}



i was not clear why 'Caught MyParentException' not called. since MyChildException extends MyParentException. How compil;e time error different from earlier progarm ion previous question without compiler error please advise
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
will have already been called by the first block=will have already been caught by the first block
Avatar of gudii9

ASKER

>>>The compiler knows that MyChildException will have already been called by the first block, since the first block that's type-correct does the business.

>>will have already been called by the first block=will have already been caught by the first block

what you mean by first block. you mean first catch block?



>>>

    public static void main(String[] args) {
        try {
            throw new MyChildException();
        } catch (MyParentException s) {
            System.err.println("Caught MyParentException");
        } catch (MyChildException a) {   // Compile error expected
            System.err.println("Caught MyChildtException");
        }
    }
}

i thought MyChildException in second block is called here. please advise
Avatar of gudii9

ASKER

>>The compiler knows that MyChildException will have already been called by the first block, since the first block that's type-correct does the business


can you please let me what do you mean by first block. where first bloc is calling MyChildException in this program . i am still not clear
The first block is

>>
        } catch (MyParentException s) {
            System.err.println("Caught MyParentException");
>>

which will catch MyChildException