Results 1 to 2 of 2
- 02-11-2015, 10:07 PM #1
Member
- Join Date
- Feb 2015
- Posts
- 2
- Rep Power
- 0
Creating class that throws errors
I created a class Person:
Java Code:public class Person { protected static int MAX_AGE = 150; protected static int MIN_AGE = 0; private static final String VALID_WORD_REGEXP = "[a-zA-Z]{3,30}"; private String firstName; private String lastName; private int age; Person(){ setFirstName("anonymous"); setLastName("anonymous"); setAge(18); } Person(String firstName, String lastName, int age){ setFirstName(firstName); setLastName(lastName); setAge(age); } public void setFirstName(String firstName){ if(isValidWord(firstName)){ this.firstName = firstName; }else{ throw new IllegalArgumentException("Invalid first name"); } } public void setLastName(String lastName){ if(isValidWord(lastName)){ this.lastName = lastName; }else{ throw new IllegalArgumentException("Invalid last name"); } } private boolean isValidWord(String word){ return word.matches(VALID_WORD_REGEXP); } public void setAge(int age){ if(isValidAge(age)){ this.age = age; }else{ throw new IllegalArgumentException("Age is not in a range of [" + MIN_AGE + "-" + MAX_AGE + "]"); } } private boolean isValidAge(int age){ return age >= MIN_AGE && age <= MAX_AGE; } String getFirstName(){ return firstName; } String getLastName(){ return lastName; } int getAge(){ return age; } }
Besides that I have couple questions:
- I can't quite understand throws statement. I'm thinking throws statement is for passing exceptions one level higher(with are not cought in this caller function). So that would mean I need to put throws in this function only: Java Code:
Person(String firstName, String lastName, int age)
- If so that would mean when Java Code:
Person person = new Person(.....)
- 02-11-2015, 10:39 PM #2
Re: Creating class that throws errors
Have you discovered the Oracle tutorials?
Lesson: Exceptions (The Javaâ„¢ Tutorials > Essential Classes)
dbIf you're forever cleaning cobwebs, it's time to get rid of the spiders.
Similar Threads
-
Maven throws errors pointing to settings.xml
By smoothrace in forum Apache MavenReplies: 0Last Post: 01-28-2015, 08:39 AM -
Problems calling a class with constructor throws Exception
By brrrr in forum New To JavaReplies: 4Last Post: 04-22-2012, 10:22 PM -
Creating and implementing class for creating a calendar object
By kumalh in forum New To JavaReplies: 9Last Post: 07-29-2011, 03:18 PM -
Calling on class with throws IOException
By gisler in forum NetworkingReplies: 5Last Post: 12-01-2009, 05:20 PM -
Recursive Class throws NullPointerException
By freeBatjko in forum New To JavaReplies: 5Last Post: 11-03-2009, 10:18 AM
Bookmarks