Professional Documents
Culture Documents
Week 6 Homework
Week 6 Homework
Homework 6
Ex 11.2 What would happen if the try statement were removed from the level1 method of the
ExceptionScope class in the Propagation program?
If the try statement were removed from the level1 method, then an exception would be thrown
and produce an error message because it would move to the main method which has no try
statement.
Ex. 11.3 What would happen if the try statement described in the previous exercise were moved
to the level2 method?
The exception that is thrown in level3 would move to level2. It should be caught and handled
there in that level’s catch method and the level 2 method would be allowed to finish because it
was handled.
Ex 11.4 Look up the following exception classes in the online Java API documentation and
describe their purpose:
D. PatternSyntaxException - This exception is caused when a syntax error occurs in the pattern
of a regular expression.
Exception class
//input
System.out.println("Enter a string, enter DONE when finished: ");
String input = scan.nextLine();
//exit if done
if(input.equalsIgnoreCase("DONE"))
System.exit(0);
do
{
try
{
//use throwable class
if(input.length() > 20)
throw new StringTooLongException();
}
finally
{
//repeat input if not too long or done
System.out.println("Enter another string, enter DONE when finished: ");
input = scan.nextLine();
}
}
while(!input.equalsIgnoreCase("DONE"));
scan.close();
}
}
PP 11.2 Modify the solution to PP 11.1 such that it catches and handles the exception if it is
thrown. Handle the exception by printing an appropriate message, and then continue processing
more strings.
Exception class
//input
System.out.println("Enter a string, enter DONE when finished: ");
String input = scan.nextLine();
//exit if done
if(input.equalsIgnoreCase("DONE"))
System.exit(0);
do
{
try
{
if(input.length() > 20)
throw new StringTooLongException();
System.out.println("Enter another string, enter DONE when finished: ");
input = scan.nextLine();
}
catch(StringTooLongException exception)
{
System.out.println(exception.getMessage());
System.out.println("Enter another string, enter DONE when finished: ");
input = scan.nextLine();
}
}
while(!input.equalsIgnoreCase("DONE"));
scan.close();
}
}