0

Hey everyone I have a question pertaining to a exception try-catch statement. In a practice problem I am doing, the user inputs a string of a certain length. If the user enters a string greater than the length of 20, an exception is thrown. Now I seem to have everything setup in order, but what is really confusing me is what to put in the try block. Can anyone explain in either pseudo code or through explanation in what I need to input to get it to run?

Also, I have a question pertaining to the catch statement with my catch(StringTooLongException e) . I already made two other programs that deal with an inherited class and a class that uses the name I created to solve this same problem with out a try-catch statement. That is where the StringTooLongException comes from. My question is, how do you know what exception name to use? I know there are general exceptions built into java, but I am just slightly confused.

Thanks

Here is my code:

import java.util.Scanner;

public class StringTooLongExceptionModified{

    public static void main(String[] args){
        String input;


        Scanner myScan = new Scanner(System.in);
        System.out.println("Enter a string(DONE to quit): ");
        input = myScan.nextLine();

        while(!input.equals("DONE")){

            try{




            }
            catch(StringTooLongException e){
                System.out.println ("Exceeds string length: " + input);
            }

            System.out.println("Enter a string(DONE to quit): ");
            input = myScan.nextLine();


        }
    }   
}

1 Answer 1

3

Seems like you are looking for:

try{
    if (input.length() <= 20) {
        // do stuff with your input 
    } else {
        throw new StringTooLongException("'" + input + "' is longer than 20");
    }
} catch(StringTooLongException e){
    System.out.println ("Exceeds string length: " + input);
}
Sign up to request clarification or add additional context in comments.

4 Comments

and with regards to "how do you know what exception name to use?" If your StringTooLongException class subclasses Exception then you can use catch(StringTooLongException e){ ... } Other predefined exceptions can be found through this
Thank you for the input jlordo, but now everytime I run it, it won't throw the exception. If I input more a string with more a length longer than 20, it just keeps on running. Any ideas on what can be wrong?
Also, thank you Adeeb. That cleared up the question I had pertaining to which exception name to use.
@user2045470: I only changed your try/catch block. Don't forget your following code, especially input = myScan.nextLine();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.