Page 1 of 1

[HD-OCP17/21-Fundamentals Pg 166, Sec. 6.4.4 - instance-initializers-vs-constructors]

Posted: Thu Sep 19, 2024 11:24 pm
by raphaelzintec
hello

why is this instance initializer correct ?? and compile fine??

Code: Select all

    {
        try {
            throw new Exception();
        } catch (RuntimeException e){

        }
    }
because if i put this code inside main then compiler will complain and its logic because subtype cannot catch superclass!!

Re: [HD-OCP17/21-Fundamentals Pg 166, Sec. 6.4.4 - instance-initializers-vs-constructors]

Posted: Thu Sep 19, 2024 11:27 pm
by raphaelzintec
also why is this giving error

Code: Select all

    {
        throw new Exception();
    }

    constructor() throws Exception{
    }
but this compiles fine???

Code: Select all

    {
       if(true) throw new Exception();
    }

    constructor() throws Exception{
    }

Re: [HD-OCP17/21-Fundamentals Pg 166, Sec. 6.4.4 - instance-initializers-vs-constructors]

Posted: Fri Sep 20, 2024 12:32 am
by admin
This is explained in the chapter 1. section 1.2.1