A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

IllegalArgumentException in java example

//import Scanner class
import java.util.Scanner;
// create class for age validation
class Form
{
  //define a variable
  private final int value;
 
  // constructor of class
  public Form(int v)
  {
    // check condition of age
    if (v < 0 || v > 100)
    {
      // if age exceeds range then generate exception
      throw new IllegalArgumentException(Integer.toString(v));
    }
    this.value = v;
  }

  // define function to get value of age
  public int getValue()
  {
    return value;
  }
}

class IllegalArgumentEx
{
  // define main method
  public static void main(String[] args)
  {
      // use scanner object to take input of age by user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter age: ");
      int age=sc.nextInt();
   
    // validate input age by constructor
    Form obj = new Form(age);
    System.out.println(obj.getValue());
  }
}




Another way



//import Scanner class
import java.util.Scanner;
// create class for age validation
class Form
{
  //define a variable
  private final int value;
 
  // constructor of class
  public Form(int v)
  {
    // check condition of age
    if (v < 0 || v > 100)
    {
      // if age exceeds range then generate exception
      throw new IllegalArgumentException();
    }
    this.value = v;
  }

  // define function to get value of age
  public int getValue()
  {
    return value;
  }
}

class IllegalArgumentEx
{
  // define main method
  public static void main(String[] args)
  {
      // use scanner object to take input of age by user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter age: ");
      int age=sc.nextInt();
   
    // validate input age by constructor
    Form obj = new Form(age);
    System.out.println(obj.getValue());
  }
}












LEARN TUTORIALS

.

.