Exception Handling
 
The exception handling technique
 
. Involves the use of the try, catch, and finally Java keywords
. Consists of several steps
 
 
1. try a block of code that may result in an exception being "thrown"
 
2. Code one or more blocks designed to automatically catch and handle a specific type of exception if one occurs. At most, only one of these blocks can be called in a single pass through the code. If none of the specified exceptions occurs, none of the blocks will be executed.
 
3. Optionally code a block that will finally be run in ALL situations, whether an exception occurs or not
 
 
. Has the following general syntax:
 
try
{
statements that may result in an exception being thrown;
}

catch (exception-type1 reference)
{
statements to handle the exception;
}

catch (exception-type2 reference)
{
statements to handle the exception;
}

other catch blocks...

finally
{
statements to be ALWAYS executed;
}
 
Example:
The following is a modified version of the "shell game" program presented earlier. It contains a try block and two catch blocks. One handles a NullPointerException and the other handles an ArrayIndexOutOfBoundsException. No finally block is specified, so logic comes together after the end of the last catch block.
 
public class AppExcep
{
public static void main(String[] args)
{

// Loop control variable.

char again = 'y';

// Main loop. One array is entered and processed in each iteration.

while (again == 'Y' || again =='y')
{

// Instantiate a three element array and load a single String
// at a random element location.

String[] strings = new String[3];
int randomIndex = (int) ((Math.random()*100) % strings.length);
strings[randomIndex] = "Lucky";

// Ask the user to guess the element location.

Utility.separator(50, '>');
System.out.print("Pick a number from 1 to " + strings.length + ": ");

// "Try" to read their response, use it to index into the array,
// and see if they win.

try
{

// If they guess the element location, display a message. Otherwise,
// an exception will occur.

if (strings[Keyboard.readInt() - 1].equals("Lucky"))
{
Utility.skip();
System.out.println(" YOU WIN!!!");
}
}

// This block is automatically executed if a NullPointerException
// occurs to indicate a null array location.

catch (NullPointerException err)
{
Utility.skip();
System.out.println(" Empty shell - YOU LOSE!!!");
}

// If an ArrayIndexOutOfBoundsException occurs, this block is
// automatically executed. It indicates an invalid number was
// used as an index.

catch (ArrayIndexOutOfBoundsException err)
{
Utility.skip();
System.out.println(" Invalid number - YOU LOSE");
}

// Ask the user if they want to do it again and repeat the loop as
// requested.

Utility.separator(40, '=');
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
}
}