异常处理:try-catch块错误

时间:2020-09-21 08:27:58

标签: java exception try-catch

我试图测试两个字符串的大小,并在try-catch块中捕获错误。我在包含throw语句的行中收到“找不到符号”错误。

class test {

    public static void main(String args[]) {
        String a = "abcdefghi";
        String b = "abcdefgh";

        try {
            if (a.length() != 9) {
                throw IllegalArgumentException;
            }

            if (b.length() != 10) {
                throw IllegalArgumentException;
            }
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
    }
}

image of error msg

1 个答案:

答案 0 :(得分:-1)

您需要创建抛出异常的实例

public static void main(String args[]){
    String a = "abcdefghi";
    String b = "abcdefgh";
    
    try{
        if(a.length()!=9){
            throw new IllegalArgumentException();
        }

        if(b.length()!=10){
            throw new IllegalArgumentException();
        }
    } 
    catch(IllegalArgumentException e){
        System.out.println(e);
    }
}
相关问题