异常处理try-catch语句字符串长度

时间:2013-05-01 00:59:17

标签: java exception-handling try-catch

大家好我有一个关于异常try-catch语句的问题。在我正在做的练习中,用户输入一定长度的字符串。如果用户输入的字符串长度大于20,则抛出异常。现在我似乎按顺序设置了所有内容,但真正令我困惑的是放入try块的内容。任何人都可以用伪代码或通过解释来解释我需要输入什么来让它运行?

另外,我有一个与我catch(StringTooLongException e)的catch语句有关的问题。我已经创建了另外两个处理继承类的程序和一个使用我创建的名称来解决同一个问题的类,并且没有try-catch语句。这就是StringTooLongException来自的地方。我的问题是,你怎么知道使用什么例外名称?我知道java中有一些常见的例外,但我只是有些困惑。

由于

这是我的代码:

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 个答案:

答案 0 :(得分:1)

好像你正在寻找:

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);
}
相关问题