Home Java Java-exception Constructor Exception in Java



Constructor Exception in Java
Posted on: October 23, 2008 at 12:00 AM
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

Related Tags for Constructor Exception in Java:
javacexceptionerrorconstructoriostructgeneralconstthisforprogramwritingtohandlingrameiterrorsliceinmtrjallmemeanprotorsctorishalleaexceptandarcodcodeconsstrvassrithavstctorallyprndodeonogro


More Tutorials from this section

Ask Questions?    Discuss: Constructor Exception in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.