OOPS

Assignment - 9

Objective

Write a program to demonstrate the use of only throw keyword.

Programming Language & Compilation

$ javac Program.java
$ java Program

Source Code

import java.lang.System;

class Person {
  public String name;
  public int age;

  public Person(String name, int age) {
    if (age < 0) {
      // `throw` exception if negative age is provided to constructor, before object
      // creation.
      throw new IllegalArgumentException("Age cannot be negative.");
    }
    this.name = name;
    this.age = age;
  }
}

public class Program {
  public static void main(String[] args) {
    Person p = new Person("John", -1);
    System.out.println(p.name);
    System.out.println(p.age);
  }
}

Output

right-click & select “Open image in new tab” for larger image.

WindowsTerminal_jaXtFMyfVf