1

我正在尝试使用 try/catch。我非常确定语法是正确的,但不确定为什么会出现此错误:'(' expected catch^

这是我的代码:

    Random first_number = new Random();
    Random second_number = new Random();

    int number_1;
    int number_2;

    int answer_M;
    String answer;
    int correctAnswer_M = 0;


    for(int i=1;i<=20;i++)
    {
        try
        {
            number_1 = first_number.nextInt(10);
            number_2 = second_number.nextInt(10);

            System.out.print("\n         " + i + ".) ");
            System.out.print(number_1 + " multiplied by " + number_2 +" = ");
            answer_M = Integer.parseInt(answer);

                if(answer_M==(number_1 * number_2))
                {
                    correctAnswer_M = correctAnswer_M + 1;
                }
        }
        catch
        {
            System.out.print("Please enter an answer.");
            i=i-1;
        }
    }

期待你的回复。谢谢!:)

4

3 回答 3

6

编译器(catch. 您需要添加Exception您正在捕获的内容。-

catch (Exception e)

更多关于 catch 块的信息

于 2013-10-05T22:35:25.540 回答
3

You have to catch a specific type of exception.

try {
    // Some exception throwing code here.
} catch(Exception e) {
    System.out.println("Caught exception: " + e.getMessage());
    e.printStackTrace();
}
于 2013-10-05T22:35:47.977 回答
1

您需要告诉编译器您希望捕获什么样的异常。最通用的方法是捕获一个Throwable. 例如:

try {
    // Do something
} catch (Throwable t) {
    // Handle the error
}

查看官方指南以获取更多信息。

于 2013-10-05T22:38:02.853 回答