We’re studying try-catch-finally exception handling at the moment, this is my solution from the Exercise 5-4, page 377 of SCJP 6 Study Guide (Sierra & Bates). I also used reference from this website section 1.9. I wrote the code in Notepad++ and compiled and ran it in Windows command-line.

Exception Gets Handled!

A String array of food is being tested against the try-catch. When the food ‘beans’ (as in ‘tinned beans’, which I don’t like) is tested the exception is thrown and all hell breaks loose (not really, because the exception is handled! Hurrah!)

It’s heavily commented for my own reference and yours.

//created the custom exception in an inner class,
//must extends Exception which is part of java.lang
class BadFoodException extends Exception{
//constructor takes a String argument.
//super(str) takes custom text from String when we throw new
//BadFoodException, which is printed to screen from
//ex.getMessage() in the catch block
public BadFoodException(String str){
System.out.println("BadFoodException is used when the word beans is encountered");

//primary class
public class MyException{

public static String [] array;

//main method
public static void main(String [] arg){

//create array of foods
array = new String [] {"cabbage","chips","apples","beans"};

//try-catch array elements against the custom exception
//with checkFood() doing the exception checking...
for(int i = 0; i < array.length; i++){ String myFood = array[i]; checkFood(myFood); } } catch (BadFoodException ex) { //exception handler ex.printStackTrace(); System.out.println(ex.getMessage()); } } //method checkFood() public static void checkFood(String food) throws BadFoodException{ if(food.equals("beans")){ throw(new BadFoodException("I hate beans!")); } System.out.println("yummy!"); // skip if exception is triggered } //end method }