Write a program to demonstrate the use of only throw
keyword.
$ javac Program.java
$ java Program
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);
}
}
right-click & select “Open image in new tab” for larger image.