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, 2010]");
    }
}

The new person class:


/**
This simple class describes a person: their name (first, last) and date of birth.
**/

public class PersonWithException {
	// instance variables: different for each instance 
	// of a person
	// instance variables are invisible from 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 > 2010 causes the program to throw 
	* InvalidYearException
	**/
	public PersonWithException(String firstName, String last, int year) 
	    throws InvalidYearException {
		this.firstName = firstName;
		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 > 2010) {
		    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 correspinding 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;	
	}
	
	/**
	* returns true if this person is older than the other
	* person, false otherwise
	**/
	public boolean isOlder(PersonWithException other) {
		return this.yearBirth < other.yearBirth;
	}
	
	public String toString() {
		return "PersonWithException: " + this.getFullName() 
		    + " born in " + this.yearBirth;
	}
	
}

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


public class TestPersonWithException{

    // main may throw an InvalidYearException so we must make it a part
    // of its declaration:
	public static void main(String [] args) throws InvalidYearException {
	    
	       // create a new Person
	       PersonWithException bob = 
		   new PersonWithException("Robert","Smith",1985);
	       // create another person
	       PersonWithException mary = 
		   new PersonWithException("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 = 2010;
		// expected: 25 
		System.out.println("In the year " + year + " " + bob.getFullName() +
			" turned or will turn " + bob.age(year));
		year = 2011;
		// expected: 24 
		System.out.println("In the year " + year + " " + mary.getFullName() +
			" turned or will turn " + mary.age(year));
		
		// write and test a method "isOlder" 
		// expected: bob is older than mary
		if (bob.isOlder(mary)) {
			System.out.println(bob.getFullName() + " is older than " +
				mary.getFullName());
		} else {
			System.out.println(bob.getFullName() + " is not older than " +
				mary.getFullName());
		}

                // write toString method so that a Person object 
                // can be printed directly with System.out.println
                System.out.println(bob);
                System.out.println(mary);
	}
}

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


public class TestPersonWithExceptionTwo{

	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. 
	      PersonWithException bob = null;
	      PersonWithException mary = null;
	      PersonWithException joe = null;
	       try {
		    // create a new Person
		    bob = new PersonWithException("Robert","Smith",1985);
		    // create another person
		    mary = new PersonWithException("Mary","Green", 1987);
		    joe = new PersonWithException("Joe", "Future", 2012);
	       } 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 = 2010;
		// expected: 25 
		System.out.println("In the year " + year + " " + bob.getFullName() +
			" turned or will turn " + bob.age(year));
		year = 2011;
		// expected: 24 
		System.out.println("In the year " + year + " " + mary.getFullName() +
			" turned or will turn " + mary.age(year));
		
		// write and test a method "isOlder" 
		// expected: bob is older than mary
		if (bob.isOlder(mary)) {
			System.out.println(bob.getFullName() + " is older than " +
				mary.getFullName());
		} else {
			System.out.println(bob.getFullName() + " is not older than " +
				mary.getFullName());
		}

                // write toString method so that a Person object 
                // can be printed directly with System.out.println
                System.out.println(bob);
                System.out.println(mary);
	}
}

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.