Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Constructor Exception in Java

Ads
 

Constructor Exception in Java

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

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

Ads

Ads