Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Jul 14, 1999

Causes for an InstantiationException

Question:
What can cause an InstantiationException?

Answer:
An InstantiationException is thrown when you try to create an instance of a class with Class.newInstance() and the class cannot be instantiated. This could be because there is an uninstantiable interface or abstract class. If the constructor is not public, then an IllegalAccessException will be thrown.

The following example demonstrates this:

 
class Foo {
  private Foo() { }
}

public class Instantiate {
  public static final void main(String[] args) {
    Class c;
    Object obj;

    try {
      c = Class.forName("java.lang.Cloneable");
    } catch(ClassNotFoundException e) {
      e.printStackTrace();
      return;
    }

    // Should throw InstantiationException
    try {
      obj = c.newInstance();
    } catch(InstantiationException e) {
      System.err.println("\nAn InstantiationException was thrown.\n");
      e.printStackTrace();
    } catch(IllegalAccessException e) {
      System.err.println("\nAn IllegalAccessException was thrown.\n");
      e.printStackTrace();
    } catch(SecurityException e) {
      System.err.println("\nA SecurityException was thrown.\n");
      e.printStackTrace();
    }

    try {
      c = Class.forName("Foo");
    } catch(ClassNotFoundException e) {
      e.printStackTrace();
      return;
    }

    // Should throw IllegalAccessException
    try {
      obj = c.newInstance();
    } catch(InstantiationException e) {
      System.err.println("\nAn InstantiationException was thrown.\n");
      e.printStackTrace();
    } catch(IllegalAccessException e) {
      System.err.println("\nAn IllegalAccessException was thrown.\n");
      e.printStackTrace();
    } catch(SecurityException e) {
      System.err.println("\nA SecurityException was thrown.\n");
      e.printStackTrace();
    }
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date