捕获异常后,如何继续执行 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