Citigroup Interview Question
Developer Program EngineersCountry: United States
Interview Type: Phone Interview
Exception occurs in constructor initialization itself and since the object creation failed, it wont proceed to method call. it can be Exception or RuntimeException. Below is the code
public class C {
A a;
B b;
public C() throws Exception{
//Doin initialisation to perform some DB connection
a= new A();
b= new B();
throw new RuntimeException("Error occured");
}
void displaC(){
a.displayArea();
b.displayArea();
System.out.println("display Area C");
}
public static void main(String[] args) throws Exception {
C a= new C();
a.displaC();
}
}
??? your code makes no sense?
The question is how would you handle the case where the DB connection fails to be made. Typically what you would do is the following.
1) In the constructor you would use try/catch block to handle the exception. Set the DB connection to null.
2) In each method of the class put a guard in that checks if the DB connection = null. If so then throw an exception or give some other indication that the DB connection is not valid.
2)
Sorry, hit the submit button early.
The point being that the calling class should not know anything about the internals of the class which is maintaining the DB connection.
If you let the RuntimeException propagate upwards then yes the method call will not be made, but this would be considered sloppy programming.
can we use try/catch to implement the stale object?
- Jess May 04, 2013