Base class's contructor and method throws exception, What needs to be taken care of when writing the derived class for this?

0 views
Skip to first unread message

Rohit Ghatol

unread,
Dec 6, 2007, 6:07:42 AM12/6/07
to Pune Java Interview Questions Group
See the following code

public class Base{

public void Base throws AException,BException, CExcpetion{
}

public void foo() throws AException, BException, CExcpetion{
}

}

Now I need to write a derived class of Class Base. What care needs to
be taken when writing the constructor of Derived class and overriding
method foo in the derived class.

If possible, write the complete Derived class (lets name the class as
Derived).

Rohit Ghatol

unread,
Dec 6, 2007, 6:08:42 AM12/6/07
to Pune Java Interview Questions Group
Note AException,BException and CException are totally independent of
each other.

Undertaker

unread,
Dec 6, 2007, 6:59:44 AM12/6/07
to Pune Java Interview Questions Group
I left Java since 2004 but this is what I can guess.

Good way for handling exceptions thrown in constructor:

class Derived : Base
{
private Derived(int n)
: Base(n)
{
}

public static Derived Create(int n)
{
try
{
return new Derived(n);
}
catch( AException )
{
throw;
}
catch( BException )
{
throw;
}
catch( CException )
{
throw;
}
}
}

You can also opt for writing Derived constructor throwing same list of
exception + more.
Regarding member overriding,

Derived-class version of a method may choose to not throw any
exceptions, even if the base-class version does. Again, this is fine
since it doesn't break any code that is written assuming the base-
class version throws exceptions.

(Please excuse me for syntax)

- Vishwesh.

Rohit Ghatol

unread,
Dec 11, 2007, 7:45:42 AM12/11/07
to Pune Java Interview Questions Group
As usual I won't give the answer right away. Its good to see people
try, I will give hints

See the following code snippets

try{

Base b = new Base();

}
catch(AException ae){
}
catch(BException be){
}
catch(CException ce){
}

So when some one creates Base b catches all the exceptions thrown by
Constructor of Base.

try{
Base b = new Derived();

}
catch(AException ae){
}
catch(BException be){
}
catch(CException ce){
}

Now seeing this code, try and answer, really can we throw more
exceptions in Derived constructor

Now see the following code

public class Derived extends Base{

public void Derived ....................................{
//No code here but then the compiler inserts a super
automatically, which throws 3 exception
}

}

Try to see what I am trying to say.

Regards,
Rohit
Reply all
Reply to author
Forward
0 new messages