I have an assignment to make my own exception. The exception need to be thrown when the user enters a string longer than 31 characters. Then next, task and the one I am struggling with is to do the same, but this time correctly handle the exception gracefully.
StringTooLongException.java
public class StringTooLongException extends Exception {
public StringTooLongException(String message) {
super(message);
}
}
TooLongCrashes.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TooLongCrashes {
public static void main(String[] args) throws StringTooLongException, IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String message;
boolean c = true;
while(c) {
stdin = new BufferedReader(new InputStreamReader(System.in));
message = stdin.readLine();
if(message.length() >= 32)
throw (new StringTooLongException(message));
else
System.out.println(message);
}
}
}
TooLogHandled.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TooLongHandled {
static TooLongCrashes too;
public static void main(String[] args) throws StringTooLongException, IOException {
try {
too = new TooLongCrashes();
} catch(Exception e) {
System.out.println(too.toString());
}
}
}
In TooLongHandled.java I cannot seem to figure out how I should go about handling the exception.