I'm trying to create a program for class that throws an exception if the string entered is longer than 20 characters. Once the exception is thrown, it is supposed to continue and say: "Do you want to enter another line?" But, it keeps ending prematurely after the exception is thrown.
Here's my program:
Code:
/*
CS182
Excercise 5
Ashley Glasser
4/30/2011
*/
// Excercise 5 MessageTooLong.java
import java.util.Scanner;
public class MessageTooLong extends Exception {
public static void main(String args[])
throws MessageTooLongException
{
Scanner keyboard = new Scanner(System.in);
String line;
char preference;
int length;
boolean go = true;
while (go) {
System.out.println("Enter a line of text.");
System.out.println("Use no more than 20 characters.");
line = keyboard.next();
length = line.length();
if (length <= 20)
{
System.out.println("You entered " + length + " characters, which is an acceptable length.");
System.out.println("Would you like to enter another line?");
System.out.println("Enter 'y' to continue or 'n' to quit.");
preference = keyboard.next().charAt(0);
if ((preference == 'y') || (preference == 'Y')) {
go = true;
} else {
go = false;
}
}
if (length > 20)
{
throw new MessageTooLongException();
}
}
}
}
And here's my exception:
Code:
public class MessageTooLongException extends Exception
{
public MessageTooLongException()
{
super("Message Too Long!");
}
public MessageTooLongException(String message)
{
super(message);
System.out.println("Message Exception invoked with an argument.");
}
}
Why is it closing out the program?