我正在尝试使用try / catch。我非常确定语法是正确的但不确定为什么我会收到这个错误:'('expect 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;
}
}
期待您的回复。谢谢! :)
答案 0 :(得分:5)
答案 1 :(得分:3)
您必须捕获特定类型的异常。
try {
// Some exception throwing code here.
} catch(Exception e) {
System.out.println("Caught exception: " + e.getMessage());
e.printStackTrace();
}
答案 2 :(得分:1)
您需要告诉编译器您期望捕获的异常类型。最普遍的一个是抓住Throwable
。 e.g:
try {
// Do something
} catch (Throwable t) {
// Handle the error
}
有关详细信息,请查看official guide。