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

2018-10-26

posted Oct 25, 2018, 9:32 PM by Konstantinovich Samuel   [ updated Oct 29, 2018, 6:00 AM ]
Goal: Exceptions

How do we create meaningful error messages?
EXCEPTIONS!

Why Use Exceptions? 
Exceptions standardize error handling. Exceptions separate error handling code from regular code. 

How to use exceptions? 

We have all encountered an index out of bounds exception. Let us see how to use an exception instead of letting it crash, or "handle the exception".

try{
    //code that could possibly throw an exception
}catch( NameOfException variableName){
    //instead of crashing
    //when a MATCHING exception occurs.
    //run this block of code
}



public class demo
{
  public static void main(String[] args)
  {
    int[]ary = {1,9,4,5,3,0};
    
    //first example, the exception will not break out of the 
    //loop to get to the catch statement.
for(int i = 0; i < 10; i ++){ try{ System.out.print("Trying: "); System.out.print(ary[i]+ " "); }catch(ArrayIndexOutOfBoundsException e){
        //when I go past the end dont stop the program, 
        //instead run this code
} }

    System.out.println("\n");
    
    //second example, the exception will exit the loop
    //when jumping to the catch statement.
try{ for(int i = 0; i < 10; i ++){ System.out.print("Trying: "); System.out.print(ary[i]+ " "); } }catch(ArrayIndexOutOfBoundsException e){
        //when I go past the end don't stop the program,
        //instead print what e shows:
        e.printStackTrace();
} System.out.println(); } }


Runtime errors that stop your program:





The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. 

Syntax:

throw InstanceOfExceptionClass 

e.g.

throw new IndexOutOfBoundsException();
throw new UnsupportedOperationException();

But this exception i.e, Instance must be of type Throwable or a subclass of Throwable

For example, Exception is a sub-class of Throwable 

The flow of execution of the program stops immediately after the throw statement is executed 

and the nearest enclosing try block is checked to see if it has a catch statement that matches 

the type of exception. If it finds a match, control is transferred to that statement otherwise 

next enclosing try block is checked and so on. If no matching catch is found then the default 

exception handler will halt the program.'


Java program that demonstrates the use of throw
class ThrowExcep
{
    static void fun(String o)
    {
        if(o==null)
            throw new IllegalArgumentException("demo");
        else
            System.out.println(o);   
    }
  
    public static void main(String args[])
    {
        try
        {
            fun("Fish");
            fun(null);
            fun("Cat");
        }
        catch(IllegalArgumentException e)
        {
            System.out.println("Caught a problem in main.");
        }
    }
}

OUTPUT:

Fish
Caught a problem in main.

Assignment: Due Tuesday
Modify your SuperArray

SuperArray
Add one extra constructor:
    SuperArray(int startingCapacity) -> this chooses the array size in the beginning. Since 0 is a valid size, your resize must double the old size and add 1.

change some others:

0. CONVERT Your printed error messages in SuperArray into exceptions.

1.  add(int index, String element)   -> IndexOutOfBoundsException

2.  remove(int index)   -> IndexOutOfBoundsException

3.  get/set -> IndexOutOfBoundsException

Modify your driver to check for errors using the exception handling!

Comments