捕获异常后,如何继续执行Java程序?捕获异常后继续执行程序执行
我做了一个程序,要求用户输入一个数字,它会返回该数字除以生成的随机数。但是,如果用户输入字母'a',则会发生异常。
如何让程序继续执行而不是在捕获异常后终止?
do{ //Begin of loop
try{ //Try this code
System.out.println("Enter a number");
double i = read.nextDouble(); //Reads user input
double rn = r.nextInt(10); //Generates random number rn
System.out.println(i + " divided by random number " + rn + " is " + (i/rn));
}catch(InputMismatchException type_error){ //Catches error if there is a type mismatch
//Example error: if user enters a letter instead of a double
System.out.println("Error. You cannot divide a letter by a number!");
break; //break stops the execution of the program
}
//using a continue statement here does not work
}while(true); //Loop forever
用'continue'交换'break'? – Mena
使用continue进行交换中断会在一次输入后终止循环。 –
Juste消除“休息”应该够了。 – Berger