Java exceptions

Java exceptions are error messages. They may stop a program entirely, or they may be dealt with (caught) and the program will continue.

Below is the revisited Person example, now with an exception to handle invlaid year.

This is how the exception is declared. Exceptions are objects, they extend a standard java class Exception.


public class InvalidYearException extends Exception {
    public InvalidYearException(int year) {
	// a call to the construtor of the superclass Exception
	super("Year " + year + " is outside of valid range [0, 2011]");
    }
}

The new person class:


/**
 * This simple class describes a person: their name (first, last) and date of
 * birth.
 **/
public class Person {
	// instance variables (a.k.a. fields):
	// different for each instance of a person
	// private variables are invisible outside of the
	// Person class: no other part of the program can change them
	// or even see them
	private String firstName;
	private String lastName;
	private int yearBirth; // for simplicity only have year

	// Constructor method
	// note: no return type, not even void
	/**
	 * creates a person with the given first and last names and a given year of
	 * birth A year that's < 0 or > 2017 causes the program to exit
	 **/
      public Person(String first, String last, int year)
              throws InvalidYearException {
		firstName = first;
		lastName = last;
		// check if the year is valid, exit the program if
		// it's not. We will learn a better approach to error
		// handling later, but this will do for now
		if (year < 0 || year > 2017) {
		    throw new InvalidYearException(year);
		}
		yearBirth = year;
	}

	/**
	 * returns the person's first name
	 **/
	public String getFirstName() {
		return firstName;
	}

	/**
	 * returns the person's last name
	 **/
	public String getLastName() {
		return lastName;
	}

	/**
	 * returns the person's full name: concatenation of their first and last
	 * name separated by a space, e.g. Robert Smith
	 **/
	public String getFullName() {
		return firstName + " " + lastName;
	}

	/**
	 * the method changes the first and the last name of the person to the given
	 * strings. If the new first name or the the new last name is an empty
	 * string "" then the corresponding name is not changed
	 **/
	public void changeName(String newFirst, String newLast) {
		if (!newFirst.equals("")) {
			firstName = newFirst;
		}
		if (!newLast.equals("")) {
			lastName = newLast;
		}
	}

	/**
	 * The method takes a year and returns the age the person turns in that year
	 **/
	public int age(int year) {
		return year - yearBirth;
	}
}

p> A new TestPerson class that just allows the exception to stop the program:


public class TestPerson {
	public static void main(String[] args) throws InvalidYearException {
		// create a new Person
		Person bob = new Person("Robert", "Smith", 1985);
		// create another person
		Person mary = new Person("Mary", "Green", -1987);

		System.out.println("Testing names:");

		// expect to print: Robert
		System.out.println(bob.getFirstName());
		// expect to print: Green
		System.out.println(mary.getLastName());
		// expect to print: Mary Green
		System.out.println(mary.getFullName());

		System.out.println("Changing name:");
		bob.changeName("Bob", "");
		// expect: Bob Smith
		System.out.println(bob.getFullName());

		System.out.println("Checking the age:");
		int year = 2016;
		// expected: 31
		System.out.println("In the year " + year + " " + bob.getFullName()
				+ " turned or will turn " + bob.age(year));
		year = 2017;
		// expected: 30
		System.out.println("In the year " + year + " " + mary.getFullName()
				+ " turned or will turn " + mary.age(year));
	}
}

Another version of the TestPerson class that catches the exception, prints an error message and continues.


public class TestPerson {
   public static void main(String[] args) {
	    // Need to declare the variables outside of try/catch 
	    // block so that they can be accessible outside of the 
	    // block. Need to set them to something, otherwise
	    // the compiler complains that they may not have been initialized.
	    // The only thing we can set them to (without calling a constructor)
	    // is null. 
	      Person bob = null;
	      Person mary = null;
	      Person joe = null;
	       try {
		    // create a new Person
		    bob = new Person("Robert","Smith",1985);
		    // create another person
		    mary = new Person("Mary","Green", 1987);
		    joe = new Person("Joe", "Future", 2020);
	       } catch (InvalidYearException e) {
		   System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		   System.out.println("You entered invalid year for at least one person");
		   System.out.println(e.getMessage());
		   System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
	       }

		System.out.println("Testing names:");

		// expect to print: Robert
		System.out.println(bob.getFirstName());
		// expect to print: Green
		System.out.println(mary.getLastName());
		// expect to print: Mary Green
		System.out.println(mary.getFullName());

		System.out.println("Changing name:");
		bob.changeName("Bob", "");
		// expect: Bob Smith
		System.out.println(bob.getFullName());

		System.out.println("Checking the age:");
		int year = 2016;
		// expected: 31
		System.out.println("In the year " + year + " " + bob.getFullName()
				+ " turned or will turn " + bob.age(year));
		year = 2017;
		// expected: 30
		System.out.println("In the year " + year + " " + mary.getFullName()
				+ " turned or will turn " + mary.age(year));
	}
}

CSci 2101 course web site.