Try-catch造成死循环(无限递归)的问题

直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner;
public class TryCatch {
public static void main(String[] args) {
new Test1().test();
}
public static class Test1 {
Scanner input=new Scanner(System.in);
public int test(){
System.out.println("请输入:");
int temp=1;
try{
temp=input.nextInt();
}catch(Exception e){
return test();
}
System.out.println(temp);
return temp;
}
}
}

这段代码原本是想用于接收用户输入并判断输入是否合法,如果输入不合法则调用自己让用户重新输入一次数据.结果输入字符串时造成死循环 然后爆栈…

于是进入调试模式查找问题.

在调试模式中发现 input.nextInt()方法的异常在递归时并未清除而是保留下来,所以catch中的条件一直被触发,造成死循环.


解决方法:在方法中创建Scanner对象.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static class Test1 {
public int test(){
Scanner input=new Scanner(System.in);
System.out.println("请输入:");
int temp=1;
try{
temp=input.nextInt();
}catch(Exception e){
return test();
}
System.out.println(temp);
return temp;
}
}