1. Create a class BadFoodException that extends Exception class. 2. write a meth
ID: 3683391 • Letter: 1
Question
1. Create a class BadFoodException that extends Exception class.
2. write a method checkFood() that takes a string parameter and throws BadFoodException when the string represents bad food according to your own logic. For example, you may consider Chocolate a good food and Salad as a bad one! (Though nutritionists will say the opposite).
3. From the main method call, checkFood() method. Make sure you handle the BadFoodException in the main method.
4. Never ever throw any exception from the main method.
5. This program you should run from the command prompt. Take help from the links that I provided in the assignment description file. Your program should take a string parameter from the command line argument and pass it to the checkFood method.
THE CODE FOR EXCEPTION:
public class Propagate {
static String reverse(String a) throws Exception { //reverse method
if(a.length() == 0)
throw new Exception("You cannot reverse an empty string");
String b = new StringBuilder(a).reverse().toString(); //reverse string
return b;
}
public static void main(String[] args) { //main method
String string, rev;
string = args[0];
try { //try block
rev = reverse(string);
System.out.println("The reverse of the given string is"+rev+" ");
}
catch(Exception e) { //catch block
System.out.println(" " +e+" ");
}
finally {
System.out.println(" Exiting program ");
}
}
}
Explanation / Answer
class BadFoodException extends Exception { }
public class MyException
{
public static void main(String[] args)
{
if(args.length > 0)
{
try
{
for(String n : args)
{
checkFood(n);
}
}
catch(BadFoodException fe)
{
System.out.println("I don't like the food you specified.");
}
}
else
{
System.out.println("Usage: MyException foodtype1 foodtype2 ...");
}
}
static void checkFood(String s) throws BadFoodException
{
String[] foods = {"peach", "apple", "pear", "grape"};
for(String str : foods)
{
if(str.equalsIgnoreCase(s))
{
System.out.println("Yummy I like " + str);
return;
}
}
throw new BadFoodException();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.