Home Java Java-exception Constructor Exception in Java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Constructor Exception in Java

Advertisement
In this java program we are writing code for handling Constructor exception. By Handling exception we generally mean handling errors.

Constructor Exception in Java

     

In this Tutorial we want to describe you a code that help you in understanding program  for handling Constructor exception.A Constructor  mean a method which has the same name as of the class. Constructor initializes a new object belonging to the class automatically. The program given below consists of a parameterized constructor which takes String and int as a parameters. The main reason of exception occurring in the program is   ConstructorException c = new ConstructorException("gh", -1);For removing this exception we have to passs a value which is greater than 0 instead of -1..

ConstructorException.java  


public class ConstructorException {

  private static String name;
  private static int age;
  public ConstructorException(String Name, int Age) {
  name = Name;
  age = Age;
  if (age < 0) {
  throw new IllegalArgumentException("age out of range: " + age );
  }
  if (name == null) {
  throw new IllegalArgumentException(
  "name is null");
  }
  }

  public static void main(String[] args) {
  ConstructorException c = new ConstructorException("gh", -1);
  }
}

output of the program

Exception in thread "main" java.lang.IllegalArgumentException: age out of range: -1
at ConstructorException.<init>(ConstructorException.java:10)
at ConstructorException.main(ConstructorException.java:19)
Java Result: 1

Download source code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 23, 2008

Related Tutorials

Ask Questions?    Discuss: Constructor Exception in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com