Saturday, October 19, 2013

Can constructor throws Exception?

Constructors also can throw exceptions like methods: 

Let us take an example


CException.java :
public class CException{

        //Constructor 
        public  CException()throws Exception{
               //.....
        }
}

From the above code snippet, 
      A constructor also can throw an exception like a method, and the object creation logic has to handle this exception. The handling will be done using try, catch block as we use for methods..

If we try to write object creation code to the above class, we will get compilation error like..

unreported exception java.lang.Exception; must be caught or declared to be thrown
CException ce=new CException();
             ^
1 error

...So be careful in the interview...


No comments:

Post a Comment