Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

### 2018-10-29

posted Oct 29, 2018, 6:23 AM by Konstantinovich Samuel   [ updated Oct 30, 2018, 5:53 AM ]
 `Goal: Working with Exceptions ````Do now: On Paper1. Rewrite this class by adding IllegalArgumentException whenever a negative age is set.2. Compare with your neighbors, identify where/how redundant code may be eliminated (if any) class Person{ int age; public Person(int age){ this.age = age; } public void setAge(int age){ this.age = age; } }````SOLUTION:class Person{ int age; Person(int age){ setAge(age); } public void setAge(int age){ if (age<0){ throw new IllegalArgumentException("invalid age: "+age); } this.age = age; }}````DEMO EXCEPTIONS:class Person{ int age; public Person(int age){ setAge(age); } public void setAge(int age){ if ( age < 0){ throw new IllegalArgumentException("Age cannot be "+age); } this.age = age; } public static void main(String[]args){     try{ Person a = new Person(-9); int[]b = new int[1]; b[1]=3; System.out.println("A Everything is gonna be alright!"); }catch(IllegalArgumentException err){ err.printStackTrace(); System.out.println("B Handle argument"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("C Handle array"); } System.out.println("D Did not crash!"); } } ````HOMEWORK - complete your super array``Add one more constructor to your super array if you don't have it:``    public SuperArray(int initialCapacity) -> Throws:  `IllegalArgumentException` - if the specified initial capacity is negative``ArrayList:https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.htmlAP Subset:https://www2.cs.duke.edu/csed/ap/subset/doc/ap/java/util/ArrayList.html``Consider the Class Hierarchy Below```ArrayList (built in class - your super array)` \ `NoNullArrayList (not built in) \```` OrderedArrayList (not built in)``